说明:
- time模块专注于时间
- datetime相当于是对time模块的进一步封装,可以处理时间和日期,而且功能更多
1. time 模块
实例
# Python time 模块
import time
# 显示时间戳
print(f'time.time(): ', time.time()) # 结果为以秒表示的浮点数
# 睡眠
s = 1
time.sleep(s)
print(f'time.time(): {time.time()}, 间隔为两个time.time()之差,即{s}s') # 可以用这种方式计算程序消耗的时间
# 标准化为当地的 struct_time
print('time.localtime(): ', time.localtime(time.time()))
# 格式化,形如:Mon Jan 11 14:12:48 2021
print('time.ctime(): ', time.ctime())
# 字符串格式化:struct_time ——> str
print('time.strftime(): ', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
time.time(): 1610348746.780232
time.time(): 1610348747.783167, 间隔为两个time.time()之差,即1s
time.localtime(): time.struct_time(tm_year=2021, tm_mon=1, tm_mday=11, tm_hour=15, tm_min=5, tm_sec=47, tm_wday=0, tm_yday=11, tm_isdst=0)
time.ctime(): Mon Jan 11 15:05:47 2021
time.strftime(): 2021-01-11 15:05:47
2. datetime 模块
实例
```python
# Python datetime 模块
from datetime import datetime # 注意我们使用的是 datetime模块 下面的 datetime 类
# 显示当前日期和时间
print(f'datetime.now(): {datetime.now()}')
# 只显示当前日期
print(f'datetime.date(): {datetime.date(datetime.now())}')
# 只显示当前时间
print(f'datetime.time(): {datetime.time(datetime.now())}')
# 格式化日期和时间
print(f"strftime: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") # 注意这里与time模块不同:是调用strftime方法!
print(f'year:{datetime.year}, month:{datetime.month}, day:{datetime.day}, hour:{datetime.hour}, minute:{datetime.minute}, second:{datetime.second}')
datetime.now(): 2021-01-11 15:05:47.783447
datetime.date(): 2021-01-11
datetime.time(): 15:05:47.783476
strftime: 2021-01-11 15:05:47
year:<attribute 'year' of 'datetime.date' objects>, month:<attribute 'month' of 'datetime.date' objects>, day:<attribute 'day' of 'datetime.date' objects>, hour:<attribute 'hour' of 'datetime.datetime' objects>, minute:<attribute 'minute' of 'datetime.datetime' objects>, second:<attribute 'second' of 'datetime.datetime' objects>
一些备注
- 模块调用:
from datetime import datetime
- 显示当前时间:
print(datetime.now())
,其格式为<class 'datetime.datetime'>
,并非字符串 - datetime转换为str:
print(datetime.now().strftime('%Y%m%dT%H%M'))
,结果样例:20210108T1047
,中间用了一个字母T
连接(时间字符串参考:python文档)
时区转换
(暂略)
参考: