2016-06-09 99 views
-2

我有一个来自第三方(我的python程序外部)的字符串时间,我需要比较现在的时间。那个时间多久了?比较时间与时区到现在

我该怎么做?

我看过datetimetime库以及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 

类型错误:无法抵消减去天真和偏移感知日期时间

+1

请张贴你已经尝试过的一些例子,以及他们为什么没有工作。 – AidenMontgomery

回答

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 
+0

谢谢,这正是我所寻找的。现在我的恒温器将保持完美的温度! –

+0

1-你的答案假设US/Eastern有一个不变的utc偏移量 - 这是不正确的2-如果你知道输入时间在美国/东部时区,那么使用'(datetime.now(pytz.utc) - pytz.timezone ('US/Eastern')。localize(datetime.strptime(thirdPartyString,timeFmt),is_dst = None))。total_seconds()'以秒为单位查找差异。 – jfs

+0

本地化绝对是一个更好的答案,可能不得不为一个明确定义的小时/年(DST实际发生时)做一些错误处理。我的解决方案假设东部和UTC之间的差异与“now”和“thirdParty”时间相同(因此它在六个月前不会运行)。 – skier31415

0

TypeError: can't subtract offset-naive and offset-aware datetimes

要修复TypeError,使用时区意识到datetime对象:

#!/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