python datetime中的日期-时间运算

2020-01-06  本文已影响0人  AibWang

python中的常用的时间运算模块包括time,datetime,datetime支持的格式和操作更多,time模块以秒为单位计算更方便。

1. 生成一个datetime object

import datetime

# 直接通过给年、月、日、时、分、秒、毫秒、时区赋值生成(年、月、日必须给出,其余参数可以不给)
tt1 = datetime.datetime(2018, 1, 1, 12, 10, 59, 100)

# 通过 datetime.datetime.strptime 从字符串按照指定格式生成
timestr = '2019-01-14T15:22:18.123Z'
tt2 = datetime.datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S.%fZ")

# =====================================
> 2018-01-01 12:10:59.000100
> 2019-01-14 15:22:18.123000

注意:如上述例子所示,%S.%f实现了小数表示秒

2. datetime的格式:

3. 日期-时间运算

通过 datetime objecttimedelta运算

# days, seconds, microseconds, milliseconds, minutes, hours, weeks
new_dtime = tt2 + datetime.timedelta(hours=9, seconds=-10)
print("\nold time:{}".format(tt1))
print("new time:{}".format(new_dtime))

# =====================================
> old time:2018-01-01 12:10:59.000100
> new time:2019-01-15 00:22:08.123000

将datetime object转换为指定format的字符串(format根据以上第2节定义)

# transform datetime to a string
new_dtime_str = new_dtime.strftime('%Y-%m-%dT%H:%M:%S.%f')
[new_hh, new_mm] = new_dtime_str.split('T')[1].split(':')[:2]
new_ss = new_dtime_str.split('T')[1].split(':')[2][:5]
print("\nnew datetime string:" + new_dtime_str)
print("hour:%s   minute:%s   second:%s\n" % (new_hh, new_mm, new_ss))

# =====================================
> new datetime string: 2019-01-15T00:22:08.123000
> hour:00   minute:22   second:08.12

为什么要将datetime object转换为字符串呢?其实在很多情况下,我们需要将日期-时间输出为指定格式,转换为字符串更方便操作,仅需进行字符串的拆分,拼接即可实现。

参考:

https://docs.python.org/2/library/datetime.html
https://blog.csdn.net/u013215956/article/details/86478099

上一篇下一篇

猜你喜欢

热点阅读