Python全栈之路标准库系列之datetime模块

#PYTHON  2018年12月16日  295

Fast implementation of the datetime type.

功能说明
datetime.date.today()打印输出当前的系统日期
datetime.date.fromtimestamp(time.time())将时间戳转成日期格式
datetime.datetime.now()打印当前的系统时间
current_time.replace(2016,5,12)返回当前时间,但指定的值将被替换
datetime.datetime.strptime(“21/11/06 16:30”, “%d/%m/%y %H:%M”)将字符串转换成日期格式

输出当前系统时间

>>> print(datetime.date.today())
2016-05-25

将时间戳格式转换为日期格式

在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,784758214
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容
>>> time.time()
# 时间戳格式
1464156222.1887317
>>> print(datetime.date.fromtimestamp(time.time()))
# 日期格式
2016-05-25

将日期格式转换为struct_time格式

>>> current_time = datetime.datetime.now()
>>> print(current_time)
2016-05-25 14:05:26.706667
>>> print(current_time.timetuple())
# 返回struct_time格式
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=25, tm_hour=14, tm_min=5, tm_sec=26, tm_wday=2, tm_yday=146, tm_isdst=-1)

替换当前系统时间

>>> print(current_time.replace(2016,5,12))
2016-05-12 14:05:26.706667

将字符串转换成日期格式

>>> str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
>>> print(str_to_date)
2006-11-21 16:30:00

时间相加减

比现在加10天

>>> new_date = datetime.datetime.now() + datetime.timedelta(days=10)
>>> print(new_date)
2016-06-04 14:10:36.119523

比现在减10天

>>> new_date = datetime.datetime.now() + datetime.timedelta(days=-10)
>>> print(new_date)
2016-05-15 14:11:06.739814

比现在减10小时

>>> new_date = datetime.datetime.now() + datetime.timedelta(hours=-10)
>>> print(new_date)
2016-05-25 04:11:44.095624

如果你依然在编程的世界里迷茫,可以加入我们的Python学习扣qun:784758214,看看前辈们是如何学习的!交流经验!自己是一名高级python开发工程师,从基础的python脚本到web开发、爬虫、django、数据挖掘等,零基础到项目实战的资料都有整理。送给每一位python的小伙伴!分享一些学习的方法和需要注意的小细节,点击加入我们的 python学习者聚集地

比现在+120s

>>> new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)
>>> print(new_date)
2016-05-25 14:14:02.090219
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值