我是靠谱客的博主 高兴楼房,这篇文章主要介绍Python模块datetime使用指南,现在分享给大家,希望可以做个参考。

0. 引入模块
复制代码
1
import datetime
1. 获取当前时间
复制代码
1
2
3
4
now = datetime.datetime.now() print(now) today = datetime.date.today() print('today={today}'.format(today=today))
2. 和字符串的相互转换
复制代码
1
2
3
4
5
6
s = now.strftime("%Y-%m-%d %H:%M:%S") print(s) s = now.strftime("%Y-%m-%d") print(s) date = datetime.datetime.strptime(s, "%Y-%m-%d") print(date, type(date))
3. 和timestamp相互转换
复制代码
1
2
3
4
5
6
7
8
9
10
timestamp = time.time() print(timestamp) dt = datetime.datetime.fromtimestamp(timestamp) print('dt=%s, type=%s' % (dt, type(dt))) struct_time = dt.timetuple() print(struct_time) timestamp = time.mktime(struct_time) print(timestamp) s = time.strftime("%Y-%m-%d %H:%M:%S", struct_time) print(s)
4. 日期之间的计算
复制代码
1
2
3
4
5
6
7
8
9
start_date = datetime.date(2018, 1, 1) end_date = datetime.date(2018, 3, 1) delta_date = datetime.timedelta(days=1) cur = start_date while cur <= end_date: weekday = cur.isoweekday() if 1 <= weekday <= 5: print(cur.strftime("%Y-%m-%d")) cur += delta_date

最后

以上就是高兴楼房最近收集整理的关于Python模块datetime使用指南的全部内容,更多相关Python模块datetime使用指南内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(78)

评论列表共有 0 条评论

立即
投稿
返回
顶部