[python]统一转换日期格式dateutil.parser.parse

Python013

[python]统一转换日期格式dateutil.parser.parse,第1张

背景:

我有很多很多的日志数据,每个日志里面都有日期字符串,我需要将其转换为datetime格式

问题是,这些日志里的字符串格式五花八门,有2017-05-25T05:27:30.313292255Z,有2016-07-01T00:00:00以及其他各种我还没有看到的格式。

开始我写了一长串的if else来判断格式,但是总有我漏掉的。

最后上网一查,发现dateutil.parser.parse。可以不用我们指定格式,直接将字符串转换为datetime格式。

注:我试了下"19/May/2017:04:10:06 +0000" 居然失败了- -!那可能这个函数只认识数字不认得字母吧。

24点。

Python程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。Python提供了一个time和calendar模块可以用于格式化日期和时间。时间间隔是以秒为单位的浮点小数。每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。Python的time模块下有很多函数可以转换常见日期格式。

小时0到23,从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。

python中要把字符串转换成日期格式需要使用time模块中的strptime函数,例子如下:

import time

t = time.strptime('2016-05-09 21:09:30', '%y-%m-%d %h:%m:%s')

print(t)执行结果如下:

time.struct_time(tm_year=2016,

tm_mon=5,

tm_mday=9,

tm_hour=21,

tm_min=9,

tm_sec=30,

tm_wday=0,

tm_yday=130,

tm_isdst=-1)

函数说明:

第一个参数是要转换成日期格式的字符串,第二个参数是字符串的格式

函数官方文档如下:

help on built-in function strptime in module time:

strptime(...)

strptime(string, format) ->struct_time

parse a string to a time tuple according to a format specification.

see the library reference manual for formatting codes (same as

strftime()).

commonly used format codes:

%y year with century as a decimal number.

%m month as a decimal number [01,12].

%d day of the month as a decimal number [01,31].

%h hour (24-hour clock) as a decimal number [00,23].

%m minute as a decimal number [00,59].

%s second as a decimal number [00,61].

%z time zone offset from utc.

%a locale's abbreviated weekday name.

%a locale's full weekday name.

%b locale's abbreviated month name.

%b locale's full month name.

%c locale's appropriate date and time representation.

%i hour (12-hour clock) as a decimal number [01,12].

%p locale's equivalent of either am or pm.

other codes may be available on your platform. see documentation for the c library strftime function.