《0基础》学习Python——第十一讲__时间函数

一、时间函数是Python中的内置函数和模块,用于处理日期和时间相关的操作。以下是常用的时间函数的种类和用法:

1、time.time():返回当前时间的时间戳。

时间戳(timestamp)是一种表示日期和时间的方式,它是一个浮点数或整数,表示从某个特定的固定时间点(通常是1970年1月1日零点,也称为UNIX纪元)开始经过的秒数或毫秒数。在计算机编程中,时间戳常用于记录事件的发生时间、进行时间计算和比较等操作。

python 复制代码
import time

timestamp = time.time()
print(timestamp)

2、time.gtime():获取当前时间戳对应的struct_time对象

python 复制代码
import time
print(time.gmtime())
#其输出结果为:time.struct_time(tm_year=2024, tm_mon=7, tm_mday=15, tm_hour=13, tm_min=56, tm_sec=10, tm_wday=0, tm_yday=197, tm_isdst=0)

3、time.localtime()

python 复制代码
import time
print(time.localtime())
#打印结果为:time.struct_time(tm_year=2024, tm_mon=7, tm_mday=15, tm_hour=21, tm_min=57, tm_sec=32, tm_wday=0, tm_yday=197, tm_isdst=0)

tm_year:年份、tm_mon:月份、tm_mday:日期、tm_hour:小时、tim_sec:秒、tm_wday:星期、tm_yday:该年第几天、tm_isday:夏令时

4、time.ctime() :获取当前时间对应的易读结果

python 复制代码
import time
print(time.ctime())#输出结果为:Mon Jul 15 21:59:24 2024

5、time.sleep():暂停程序的执行一段时间。

python 复制代码
import time

print("Start")
time.sleep(2)  # 暂停2秒钟
print("End")

6、datetime.strftime(format):将日期和时间格式化为字符串

python 复制代码
from datetime import datetime
strs='今天是2024年7月15日,22时10分10秒'
str_time = datetime.strptime(strs, "今天是%Y年%m月%d日,%H时%M分%S秒")
strss = str_time.strftime("%d.%m.%Y  %H:%M:%S")
print(strss)
#其输出结果为15.07.2024  22:10:10

其中**%Y表示年,%m表示月,%d表示日,%H表示时,%M表示分,%S表示秒**

7、字符串转化成时间类型后,用str_time.year, str_time.month, str_time.day, str_time.hour, str_time.minute, str_time.second,str_time.microsecond 分别提取其中的数据,并分别表示为**年、月、日、时、分、秒、微秒,并且以整数的形式(int)**返回

python 复制代码
str_time = datetime.strptime(strs, "%Y-%m-%d %H:%M")
print(str_time.year, str_time.month, str_time.day, str_time.hour, str_time.minute, str_time.second,str_time.microsecond)

8、datetime.now(): 返回当前的日期和时间

python 复制代码
import datetime

current_datetime = datetime.datetime.now()
print(current_datetime)

其输出结果为:

9、datetime.strptime(string, format):将字符串解析为时间对象。

python 复制代码
import datetime

date_string = "2021-01-01"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(date_object)  #输出为2021-01-01 00:00:00
                 

10、str _time. timestamp :返回当前时间的时间戳,str_time为时间类型

python 复制代码
from datetime import datetime
strs='今天是2024年7月15日,22时10分10秒'
str_time = datetime.strptime(strs, "今天是%Y年%m月%d日,%H时%M分%S秒")
print(str_time.timestamp())
相关推荐
东风破1374 分钟前
DM8达梦共享存储集群DSC搭建步骤
数据库·学习·dm达梦数据库
Jetev26 分钟前
如何确定SQL字段是否为空_使用IS NULL与IS NOT NULL
jvm·数据库·python
蛐蛐蛐40 分钟前
昇腾910B4上安装新版本CANN的正确流程
人工智能·python·昇腾
星幻元宇VR40 分钟前
VR科普大空间:沉浸式公共教育新模式
科技·学习·安全·vr·虚拟现实
m0_702036531 小时前
mysql如何处理不走索引的OR查询_使用UNION ALL优化重写
jvm·数据库·python
代钦塔拉1 小时前
Qt4 vs Qt5 带参数信号槽的连接方式详解
开发语言·数据库·qt
2401_846339561 小时前
MySQL在云环境如何选择存储类型_SSD与高性能云盘配置建议
jvm·数据库·python
2601_957780842 小时前
Claude 4.6 对阵 GPT-5.4:2026 开发者大模型 API 选型深度解析
人工智能·python·gpt·ai·claude
2601_957780842 小时前
GPT-5.5 深度解析:2026年4月OpenAI旗舰模型的技术跨越与商业决策指南
大数据·人工智能·python·gpt·openai
zhaoyong2222 小时前
SQL如何统计每个用户的首次行为时间_MIN聚合与分组
jvm·数据库·python