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、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模块的资料请关注其它相关文章!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python datetime模块的使用示例”评论...
更新日志
2024年07月03日
2024年07月03日
- 华语流行S.H.E《12CD》2001~2010[APE+CUE][3.7GB]
- 北风之望饮品怎么调配?饮品调酒配方分享
- 原画壁纸及美图第254期,无水印可自取
- 原画壁纸及美图第255期,无水印可自取
- 群星.1991-宝丽金冬日浓情【宝丽金】【WAV+CUE】
- 胡杨林.2006-香水有毒【太格印象】【WAV+CUE】
- 陈晓东.2002-从未忘记2CD【环球】【WAV+CUE】
- 绝区零珂蕾妲阵容怎么搭配好 珂蕾妲队伍搭配攻略
- 绝区零暴击鸣徽有哪些 绝区零暴击鸣徽效果介绍
- 魔兽世界奥格瑞玛法师训练师在哪 奥格瑞玛法师训练师位置介绍
- 《艾尔登法环》dlc带电祷告位置介绍
- 《幻兽帕鲁》泰锋boss坐标位置介绍
- 《山河旅探》6月份更新内容介绍
- 群星.2012《高雄国际Hi-End音响大展纪念发烧金碟(最响宣言)》[WAV分轨].
- 黄宣2021-Beanstalk[否极泰来][WAV+CUE]