• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python datetime模块的使用示例

python 搞代码 4年前 (2022-01-07) 27次浏览 已收录 0个评论
文章目录[隐藏]

这篇文章主要介绍了Python datetime模块的使用示例,帮助大家更好的理解和使用python处理时间,感兴趣的朋友可以了解下

1、获取当前年月日时分秒

 # -*- encoding=utf-8 -*- import datetime now = datetime.datetime.now() print("now:{}".format(now)) year = now.year print("year:{}".format(year)) month = now.month print("month:{}".format(month)) day = now.day print("day:{}".format(day)) hour = now.hour print("hour:{}".format(hour)) minute = now.minute print("minute:{}".format(minute)) second = now.second print("second:{}".format(second))

2、datetime转为string

 # -*- encoding=utf-8 -*- import datetime now = datetime.datetime.now() print('type:{}'.format(type(now))) print('now datetime:{}'.format(now)) now_string = now.strftime('%Y-%m-%d %H:%M:%S') print('type:{}'.format(type(now_string))) print('now string:{}'.format(now_string))

3来源gao($daima.com搞@代@#码(网、string转为datetime

 # -*- encoding=utf-8 -*- import datetime time_str = '2021-01-28 10:51:26' time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') print('type:{}'.format(type(time_date))) print(time_date)

4、时间相加

 # -*- encoding=utf-8 -*- import datetime time_str = '2021-01-28 10:00:00' time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') print('原始时间:\t\t\t\t{}'.format(time_date)) add_info = datetime.timedelta(days=1, hours=2, minutes=3, seconds=4) add_end = time_date + add_info print('加上1天2个小时3分钟4秒后:\t{}'.format(add_end))

 5、时间相减

①两个时间差

 # -*- encoding=utf-8 -*- import datetime time_str = '2021-01-28 10:00:00' time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') print('原始时间:\t{}'.format(time_date)) time_str = '2021-05-29 12:12:12' time_date2 = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') print('原始时间2:\t{}'.format(time_date2)) time_date3 = time_date2 - time_date print('时间差:{}'.format(time_date3))

②减去1天2个小时3分钟4秒(加负数)

 # -*- encoding=utf-8 -*- import datetime time_str = '2021-01-28 10:00:00' time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S') print('原始时间:\t\t\t\t{}'.format(time_date)) add_info = datetime.timedelta(days=-1, hours=-2, minutes=-3, seconds=-4) add_end = time_date + add_info print('减去1天2个小时3分钟4秒后:\t{}'.format(add_end))

以上就是Python datetime模块的使用示例的详细内容,更多关于Python datetime模块的资料请关注gaodaima搞代码网其它相关文章!

以上就是Python datetime模块的使用示例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python datetime模块的使用示例
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址