模块datetime

四个大类:

datetime:日期时间对象;(年/月/日 时:分:秒)
timedelta:时间段;
date:日期对象;(年/月/日)
time:时间对象;(时:分:秒)
格林位置时间:从1970年1月1日 00:00:00开始
图片说明

from datetime import datetime,timedelta,date,time
#date
t_1 = date(2018,11,21)
print(t_1)

#time
t_2 = time(11,21,00)
print(t_2)

#datetime
t_3 = datetime(2018,11,21,11,21)
print(t_3)

#timedelta
t_4 = timedelta(days=1)
print(t_4)

#获取当前时间now()
t_5 = datetime.now()
print(t_5)

#获取格林威治时间
t_6 = datetime.utcnow()
print(t_6)

#解析时间(字符串转化为datetime)
t_7 = datetime.strptime('2018-11-21 11:21:00','%Y-%m-%d %H:%M:%S')
print(t_7)
#格式化时间(datetime转化为字符串)
t_8 = t_7.strftime('%Y-%m-%d')
print(t_8)

#时间运算
today = datetime.now()    #获取当前时间
tomorrow = today.date()+timedelta(days=1)
yesterday = today.date()-timedelta(days=1)
print(today.date())
print(tomorrow)
print(yesterday)

运行结果:
2018-11-21
11:21:00
2018-11-21 11:21:00
1 day, 0:00:00
2018-11-22 00:40:04.160768
2018-11-21 16:40:04.160795
2018-11-21 11:21:00
2018-11-21
2018-11-22
2018-11-23
2018-11-21

from datetime import datetime
first_date=datetime.strptime('2014-7-1','%Y-%m-%d')
print(first_date)

2014-07-01 00:00:00

全部评论

相关推荐

投递腾讯等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务