您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:Python datetime模块的使用示例

51自学网 2021-10-30 23:01:39
  python
这篇教程Python datetime模块的使用示例写得很实用,希望能帮到您。

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

# -*- encoding=utf-8 -*-import datetimenow = datetime.datetime.now()print("now:{}".format(now))year = now.yearprint("year:{}".format(year))month = now.monthprint("month:{}".format(month))day = now.dayprint("day:{}".format(day))hour = now.hourprint("hour:{}".format(hour))minute = now.minuteprint("minute:{}".format(minute))second = now.secondprint("second:{}".format(second))

2、datetime转为string

# -*- encoding=utf-8 -*-import datetimenow = 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 datetimetime_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 datetimetime_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_infoprint('加上1天2个小时3分钟4秒后:/t{}'.format(add_end))

 5、时间相减

①两个时间差

# -*- encoding=utf-8 -*-import datetimetime_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_dateprint('时间差:{}'.format(time_date3))

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

# -*- encoding=utf-8 -*-import datetimetime_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_infoprint('减去1天2个小时3分钟4秒后:/t{}'.format(add_end))

以上就是Python datetime模块的使用示例的详细内容,更多关于Python datetime模块的资料请关注51zixue.net其它相关文章!


Python基于argparse与ConfigParser库进行入参解析与ini parser
python向xls写入数据(包括合并,边框,对齐,列宽)
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。