欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python【时间运算】

程序员文章站 2024-03-24 11:54:34
...

Catalog

datetime模块

In [1]: import datetime

In [2]: datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
Out[2]: '2018-08-24 19:03'

In [3]: (datetime.datetime.now()-datetime.timedelta(hours=1)).strftime('%Y-%m-%d %H:%M')
Out[3]: '2018-08-24 18:03'

示例:获取2小时前的时间

import datetime
r = '2小时前'.replace('前', '')
if '小时' in r:
    r = datetime.timedelta(hours=int(r.replace('小时', '')))
elif '分钟' in r:
    r = datetime.timedelta(minutes=int(r.replace('分钟', '')))
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
past = (now - r).strftime('%Y-%m-%d %H:%M:%S')
print(now)
print(past)

2018-08-24 19:11:09
2018-08-24 17:11:09

通用版

import datetime
relative_time = '3天'
units = [('天', 'days'), ('小时', 'hours'), ('分钟', 'minutes'), ('秒', 'seconds')]
for unit in units:
    if unit[0] in relative_time:
        relative = relative_time.replace(unit[0], '')
        relative = eval('datetime.timedelta(%s=%s)' % (unit[1], relative))
        print(relative)
        now = datetime.datetime.now()
        print(now)
        past = (now - relative).strftime('%Y-%m-%d %H:%M:%S')
        print(past)
        break

3 days, 0:00:00
2018-08-24 19:20:42
2018-08-21 19:20:42