首页 > 解决方案 > Python中的日期时间

问题描述

我有两个约会

'2017-03-10 19:01:27'
'2017-03-11 07:35:55'

我想有一天得到差异。如何在考虑时区的情况下做到这一点?

因为我们不知道这些日期的时区。我是 Python 新手

我有:

from_zone = tz.tzutc()
to_zone = tz.tzlocal()

date_first = datetime.strptime(args[0], time_format)
date_second = datetime.strptime(args[1], time_format)

rep_date_first = date_first.replace(tzinfo=from_zone)
rep_date_second = date_second.replace(tzinfo=from_zone)

timezone_date_first = rep_date_first.astimezone(to_zone)
timezone_date_second = rep_date_second.astimezone(to_zone)

day = timezone_date_first.day - timezone_date_second.day

day return me 0,如何解决?请帮我

标签: pythonpython-3.xdatetime

解决方案


arrow模块是每个处理日期的人的好朋友,你很容易实现转变。

import arrow
dt = arrow.get('2017-03-10 19:01:27')
dt = dt.replace(tzinfo='Europe/Warsaw')
dt2 = dt.shift(days=-1)
assert dt2.isoformat() == '2017-03-09T19:01:27+01:00'

你问的有点友好:I would like to get the difference one day你的代码不能单独运行(args[0]),但我认为你可以假设日期在同一个时区。


推荐阅读