将时间与时区比较为n

2024-10-08 19:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串时间来自第三方(我的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 

TypeError:无法减去偏移量naive和offset aware datetime


Tags: 方法字符串程序datetimetime时间dtnow
2条回答

问得好扎克!我自己也有这个问题。在

下面是一些代码:

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

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。在

相关问题 更多 >

    热门问题