我有来自第三方的字符串时间(我的python程序外部),我需要比较现在的时间。那个多久以前的时间?
我该怎么做?
我查看了datetime
和time
库以及pytz
,但无法找到明显的方法来执行此操作。它应该自动包含DST,因为第三方没有明确说明其偏移量,只有时区(美国/东部)。
我试过这个,但它失败了:
dt = datetime.datetime.strptime('June 10, 2016 12:00PM', '%B %d, %Y %I:%M%p')
dtEt = dt.replace(tzinfo=pytz.timezone('US/Eastern'))
now = datetime.datetime.now()
now - dtEt
TypeError:无法减去offset-naive和offset-aware datetimes
答案 0 :(得分:0)
好问题扎克!我自己也遇到过这个问题。
以下是一些代码:
from datetime import datetime
import time
import calendar
import pytz
def howLongAgo(thirdPartyString, timeFmt):
# seconds since epoch
thirdPartySeconds = calendar.timegm(time.strptime(thirdPartyString, timeFmt))
nowSecondsUTC = time.time()
# hour difference with DST
nowEastern = datetime.now(pytz.timezone('US/Eastern'))
nowUTC = datetime.now(pytz.timezone('UTC'))
timezoneOffset = (nowEastern.day - nowUTC.day)*24 + (nowEastern.hour - nowUTC.hour) + (nowEastern.minute - nowUTC.minute)/60.0
thirdPartySecondsUTC = thirdPartySeconds - (timezoneOffset * 60 * 60)
return nowSecondsUTC - thirdPartySecondsUTC
howLongAgo('June 09, 2016 at 06:22PM', '%B %d, %Y at %I:%M%p')
# first argument always provided in ET, either EDT or EST
答案 1 :(得分:0)
TypeError:无法减去offset-naive和offset-aware datetimes
要修复TypeError
,请使用时区感知日期时间对象:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
tz = pytz.timezone('US/Eastern')
now = datetime.now(tz) # the current time (it works even during DST transitions)
then_naive = datetime.strptime('June 10, 2016 12:00PM', '%B %d, %Y %I:%M%p')
then = tz.localize(then_naive, is_dst=None)
time_difference_in_seconds = (now - then).total_seconds()
is_dst=None
会导致模糊/不存在时的异常。您也可以使用is_dst=False
(默认)或is_dst=True
,请参阅python converting string in localtime to UTC epoch timestamp。