python datetime使用_Python datetime模块的使用示例

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))

870310eca53e9ec91926e84334dcd67c.png

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))

9579bb83ca32c6749b6617e7d1513108.png

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)

635c52a6d0d60f8960e4b2309fc6d6f3.png

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))

61a76217367705f2491e34472120bad4.png

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))

7c39cccee179b052a93cacb45aec8d10.png

②减去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))

ba7f38eb6d9077bfbc27699ad2adebd1.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值