How to convert dates with alphabetic months to timestamp

╄→尐↘猪︶ㄣ 提交于 2020-01-05 04:58:37

问题


What is the most efficient way to convert list itmes like

02/Oct/2013:20:18:18

to timestamp, using Python? I need to convert HUGE log files in which lines are going to be processed based on their timestamps. so need a really fast transformation method.


回答1:


strptime is the way to go. It will accept arbitrary time formats and convert it into a struct_time type object.

Additionally, you can use time.mktime() to get the unix-timestamp from the struct_time object.

EDIT: (Adding example)

Taking your example data, you'd do something like this (python shell:

>>> time.strptime("02/Oct/2013:20:18:18", "%d/%b/%Y:%X")
    time.struct_time(tm_year=2013, tm_mon=10, tm_mday=2, tm_hour=20, tm_min=18, tm_sec=18, tm_wday=2, tm_yday=275, tm_isdst=-1)
>>> time.mktime(time.strptime("02/Oct/2013:20:18:18", "%d/%b/%Y:%X"))
    1380725298.0

BTW, if you need to understand the format specifiers for the date, have a look at the date manpage.




回答2:


simply use python datetime

from datetime import datetime
datetime.strptime('02/Oct/2013:20:18:18','%d/%b/%Y:%H:%M:%S')


来源:https://stackoverflow.com/questions/19150768/how-to-convert-dates-with-alphabetic-months-to-timestamp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!