比较Python中的日期 - 如何处理时区修饰符 [英] Comparing dates in Python - how to handle time zone modifiers
问题描述
我在做Python日期比较:
假设我有一个这样的日期:'Fri Aug 17 12:34:00 2012 + 0000'
我以下列方式解析:
dt = datetime.strptime('Fri Aug 17 12:34:00 2012 +0000','%a%b%d%H:%M:%S%Y +0000')
我在文档页面找不到如何处理剩余的 +0000
?
我想要一个更通用的解决方案,然后硬编码的价值。
也许这是很容易,任何提示?
默认的 datetime
>处理时区非常好;超出您当前的机器时区和UTC,它们基本上不受支持。
您必须使用外部库或手动处理时区偏移。 >
外部库选项:
-
使用
dateutil.parser
可以处理任何日期和时间格式小心抛出:from dateutil import parser
dt = parser.parse(s)
-
iso8601
library 仅处理ISO 8601格式,其中包括相同格式的时区偏移量:import iso8601
datetimetext,tz = s.rsplit(无,1)#只抓住时区部分。
timezone = iso8601.iso8601.parse_timezone('{}:{}'。format(tz [:3],tz [3:]))
dt = datetime.strptime(datetimetext,'%a %b%d%H:%M:%S%Y')。replace(tzinfo = timezone)
演示每种方法:
>>> import datetime
>>>> s ='Fri Aug 17 12:34:00 2012 +0000'
>>>导入iso8601
>>>> timezone = iso8601.iso8601.parse_timezone('{}:{}'。format(tz [:3],tz [3:]))
>>> datetime.datetime.strptime(datetimetext,'%a%b%d%H:%M:%S%Y')replace(tzinfo = timezone)
datetime.datetime(2012,8,17, 34,tzinfo =< FixedOffset'+00:00'>)
>>>> from dateutil import parser
>>>> parser.parse(s)
datetime.datetime(2012,8,17,12,34,tzinfo = tzutc())
I am doing Python date comparizon:
Assume I have a date like this: 'Fri Aug 17 12:34:00 2012 +0000'
I am parsing it in the following manner:
dt=datetime.strptime('Fri Aug 17 12:34:00 2012 +0000', '%a %b %d %H:%M:%S %Y +0000')
I could not find on the documentation page how to handle the remaining +0000
?
I want to have a more generic solution then hardcoded value.
Perhaps this is quite easy, any hint?
The default datetime
module does not handle timezones very well; beyond your current machine timezone and UTC, they are basically not supported.
You'll have to use an external library for that or handle the timezone offset manually.
External library options:
Use
dateutil.parser
can handle just about any date and or time format you care to throw at it:from dateutil import parser dt = parser.parse(s)
The
iso8601
library handles only ISO 8601 formats, which include timezone offsets of the same form:import iso8601 datetimetext, tz = s.rsplit(None, 1) # only grab the timezone portion. timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:])) dt = datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)
Demonstration of each approach:
>>> import datetime
>>> s = 'Fri Aug 17 12:34:00 2012 +0000'
>>> import iso8601
>>> timezone = iso8601.iso8601.parse_timezone('{}:{}'.format(tz[:3], tz[3:]))
>>> datetime.datetime.strptime(datetimetext, '%a %b %d %H:%M:%S %Y').replace(tzinfo=timezone)
datetime.datetime(2012, 8, 17, 12, 34, tzinfo=<FixedOffset '+00:00'>)
>>> from dateutil import parser
>>> parser.parse(s)
datetime.datetime(2012, 8, 17, 12, 34, tzinfo=tzutc())
这篇关于比较Python中的日期 - 如何处理时区修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!