我有一个字符串“Fri, 31 Dec 1999 23:59:59 GMT”,它来自 retry-after。
我想将其与今天的日期时间进行比较。
我不明白如何使用 GMT。
谁能帮帮我吗?
最佳答案
import datetime as dt
import dateutil.parser as parser
import pytz
date_string="Fri, 31 Dec 1999 23:59:59 GMT"
then=parser.parse(date_string)
eastern=pytz.timezone('US/Eastern')
now=eastern.localize(dt.datetime.now())
print(repr(then))
# datetime.datetime(1999, 12, 31, 23, 59, 59, tzinfo=tzutc())
print(repr(now))
# datetime.datetime(2011, 5, 14, 15, 51, 48, 438283, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
print(then-now)
# -4152 days, 4:08:10.561717
处理时区可能很棘手。 处理任意时区转换的最简单、最可靠的方法是使用 pytz。
如果您确定 date_string
将位于 GMT 时区,那么有一种方法可以在 GMT 和本地时间之间进行转换,而无需使用 pytz
模块。
但是,请注意:虽然转换给出了正确的(原始)本地日期时间,但由于缺乏夏令时的考虑,两个原始日期时间的差异可能会相差一个小时:
import datetime as dt
import calendar
date_string="Fri, 31 Dec 1999 23:59:59 GMT"
then=dt.datetime.strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
# convert to localtime, assuming date_string is in GMT:
then=dt.datetime.fromtimestamp(calendar.timegm(then.timetuple()))
now=dt.datetime.now()
print(repr(then))
# datetime.datetime(1999, 12, 31, 18, 59, 59)
print(repr(now))
# datetime.datetime(2011, 5, 14, 15, 50, 7, 38349)
print(then-now)
# -4152 days, 3:09:51.961651
关于python 日期时间查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6004063/