string转成date_Python成为专业人士笔记–datetime与字符串string之间的互转

“专业人士笔记”系列目录:

创帆云:Python成为专业人士笔记--强烈建议收藏!每日持续更新!​zhuanlan.zhihu.com
20f61c3fcd75747e4117373f5e388eee.png

两个 date-times之间的时间间隔

 from datetime import datetime

 a = datetime(2016,10,6,0,0,0)
 b = datetime(2016,10,1,23,59,59)
 a-b
 #输出对象:datetime.timedelta,值为4 days, 0:00:01

 (a-b).days
 #输出间隔天数: 4

 (a-b).total_seconds()
 #输出间隔秒数 : 345601.0

datetime对象转化成字符串

from datetime import datetime

datetime_for_string = datetime(2016,10,1,0,0)
datetime_string_format = '%b %d %Y, %H:%M:%S'#设置转成string的对应解析格式

print(datetime.strftime(datetime_for_string,datetime_string_format))
#使用strftime函数,完成datatime到字符串之间的转换
#输出Oct 01 2016, 00:00:00

将字符串转换为datetime对象

 from datetime import datetime

 datetime_string = 'Oct 1 2016, 00:00:00'
 datetime_string_format = '%b %d %Y, %H:%M:%S' #设定解析格式
 datetime.strptime(datetime_string, datetime_string_format)
 #使用strptime函数,完成由字符串至Datatime之间的互转
 #输出对象:datetime.datetime:(2016, 10, 1, 0, 0)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值