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

Python020

[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" 居然失败了- -!那可能这个函数只认识数字不认得字母吧。

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.

用Python实现字符串和日期相互转换的方法,具体如下:这里用的分别是time和datetime函数来处理 importtime,datetime //日期转化为字符串 #datetostr //输出时间 printtime.strftime("%Y-%m-%d%X",time.localtime()) #strtodate //字符串转化为日期 t=time.strptime("2016-12-05","%Y-%m-%d") y,m,d=t[0:3] //输出时间 printdatetime.datetime(y,m,d)