datetime
:处理日期和时间
calendar
:处理日历
time
:时间的访问和转换
dateutil
:扩展时区和解析支持的第三方库
import time
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 2020-07-16 13:58:27
可以简单为
import datetime
print(datetime.date.today()) # 日期
print(datetime.datetime.now()) # 日期+时间
# 2020-07-16
# 2020-07-16 13:58:27.161542
类 | 描述 |
---|---|
date | 日期,年月日 |
time | 时间,时分秒毫秒时区 |
datetime | 日期+时间 |
timedelta | 时间间隔 |
tzinfo | 时区 |
timezone | 相对于UTC(世界标准时间)的偏移量 |
关系
object
timedelta
tzinfo
timezone
time
date
datetime
调用datetime.weekday()
或datetime.isoweekday()
from datetime import datetime
print(datetime.now().weekday()) # 周一为0,周日为6
print(datetime.now().isoweekday()) # 周一为1,周日为7
利用 datetime.timedelta
的方法 total_seconds()
获取时间间隔包含了多少秒
计算2020年春节放几天假
from datetime import date, timedelta
date1 = date(2020, 1, 24) # 开始放假
date2 = date(2020, 2, 2+1) # 开始上班
delta = date2 - date1
print(delta)
print(delta.total_seconds())
# 10 days, 0:00:00
# 864000.0
利用 datetime.timedelta
from datetime import datetime, timedelta
now = datetime.now()
after_a_week = now + timedelta(days=7)
print(now) # 2021-04-15 17:55:58.794208
print(after_a_week) # 2021-04-22 17:55:58.794208
Python 3.7 以上
from datetime import datetime
date_string = '2021-04-19 18:18:39.458818'
print(datetime.fromisoformat(date_string))
Python 3.7 以下
from datetime import datetime
def fromisoformat(date_string):
"""datetime字符串转datetime"""
return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
date_string = '2021-04-19 18:18:39.458818'
print(fromisoformat(date_string))
文件名不可以有冒号 :
import locale
import datetime
locale.setlocale(locale.LC_CTYPE, 'Chinese') # 设置语言环境
print(datetime.datetime.now())
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
print(datetime.datetime.now().strftime('%Y/%m/%d'))
print(datetime.datetime.now().strftime('%Y年%m月%d日'))
print(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
print(datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))
print(datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S_%f'))
# 2023-04-19 10:19:36.479925
# 2023-04-19 10:19:36
# 2023/04/19
# 2023年04月19日
# 20230419101936
# 20230419_101936
# 2023-04-19_10-19-36_480925
详细查阅 Format Codes
在 Linux 上可能会报错:locale.Error: unsupported locale setting
用这种
import datetime
now = datetime.datetime.now()
print(now.strftime('%Y{y}%m{m}%d{d}').format(y='年', m='月', d='日'))
import datetime
print(datetime.datetime(2021, 12, 7).timestamp()) # 1638806400.0
print(datetime.datetime.fromtimestamp(1638806400)) # 2021-12-07 00:00:00