使用 time.strptime 格式在 Python 中解析日期和时间戳 [英] Parsing date and timestamps in Python with time.strptime format
问题描述
我的云服务器以这种格式记录时间:
[17/Dec/2011:09:48:49 -0600]
要将其读入 Python 变量,我可以说:
>>>str = '17/Dec/2011:09:48:49 -0600'>>>导入时间>>>打印时间.strptime(str,"%d/%b/%Y:%H:%M:%S -0600")
结果:
time.struct_time(tm_year=2011, tm-mon=12, tm=mday=17, tm_hour=9, tm_min=48, tm_sec=49, tm_wday=5, tm_yday=351, tm_isdst=-1)
或者我可以试试
>>>mytime = time.strptime(str,"%d/%b/%Y:%H:%M:%S -0600")>>>打印 mytime.tm_hour
结果:
9
-0600
有什么作用?我希望它调整日期时间对象中的小时值?是否可以使用通配符代替对 -0600
进行硬编码?
-0600
是格林威治标准时间 (GMT) 的偏移量.正如另一个SO问题已经说过,time.strptime无法读取时区偏移量,尽管 datetime.strftime
可以生成它们.
如日期时间代码>模块的文档
,在python中有两种接近时间"的方法,naive或aware.当您只关心系统内的时间时,处理简单的时间/日期时间对象就可以了(在这种情况下,您可以按照艾伦的建议去除偏移量).当您需要将系统内的值与现实世界的时间概念进行比较时,您必须开始处理该偏移量.
处理这个问题的简单方法就是 使用 python-dateutil
.它有一个 解析函数,它会尽力模糊匹配您传入的日期字符串到多种格式并返回一个可行的日期时间实例,代表其对您的意思的最佳猜测.
通常,让软件给出最佳猜测"是一件坏事.在这种情况下,如果您的输入格式稳定,这似乎是合理的.在软件开发中处理时间很难,去购物吧.
My cloud server logs time in this format:
[17/Dec/2011:09:48:49 -0600]
To read it into Python variables, I can say:
>>>str = '17/Dec/2011:09:48:49 -0600'
>>>import time
>>>print time.strptime(str,"%d/%b/%Y:%H:%M:%S -0600")
Result:
time.struct_time(tm_year=2011, tm-mon=12, tm=mday=17, tm_hour=9, tm_min=48, tm_sec=49, tm_wday=5, tm_yday=351, tm_isdst=-1)
or I can try
>>>mytime = time.strptime(str,"%d/%b/%Y:%H:%M:%S -0600")
>>>print mytime.tm_hour
Result:
9
What does the -0600
do? I expected it to adjust the hour value in the date time object? Is there a wildcard to use instead of hard-coding the -0600
?
The -0600
is the offset from Greenwich Mean Time (GMT). As another SO question already says, time.strptime cannot read timezone offsets, though datetime.strftime
can generate them.
As explained at the start of the datetime
module's documentation, there are two ways of approaching "time" in python, naive or aware. When all you care about is time inside your system, dealing with naive time/datetime objects is fine (in which case you can strip out the offset as alan suggested). When you need to compare the values inside your system with the real world's notion of time, you have to start dealing with that offset.
The easy way to deal with this is just to use python-dateutil
. It has a parse function that will do its best to fuzzily match the date string you pass in to multiple formats and return a workable datetime instance that represents its best guess as to what you meant.
>>> from dateutil.parser import parse
>>> parse('17/Dec/2011:09:48:49 -0600', fuzzy=True)
datetime.datetime(2011, 12, 17, 9, 48, 49, tzinfo=tzoffset(None, -21600))
Normally, having software give its "best guess" is a Bad Thing. In this case, it seems justified if your input formats are stable. Dealing with time in software development is hard, just go shopping.
这篇关于使用 time.strptime 格式在 Python 中解析日期和时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!