将带有混合格式的字符串日期转换为纪元

时间:2015-10-19 07:38:06

标签: python python-2.7 date-conversion

我有日期列表,其格式如下:

01-01-13
01-12-13
1/19/2013
1/21/2013
1/21/2013
1/30/2013
02-01-13
02-02-13
02-12-13
2/13/2013
2/23/2013
...

我想将该列表转换为epoch列表(将其保存在Android上的SQLite数据库中)。所以我写了一个脚本(基于this)来转换它:

#!/usr/bin/python

import time

with open('date.txt') as f:
    mylist = f.read().splitlines() 
    for date_time in mylist:
        if "/" in date_time:
            pattern = '%d/%m/%Y'
        else:
            pattern = '%d-%m-%Y'
        epoch = int(time.mktime(time.strptime(date_time, pattern)))
        print epoch

但它在第一个条目中失败:

Traceback (most recent call last):
  File "dateconv.py", line 11, in <module>
    epoch = int(time.mktime(time.strptime(date_time, pattern)))
  File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '01-01-13\r\n' does not match format '%d-%m-%Y'
fr@Romanowski:~/Downloads$ python dateconv.py 
Traceback (most recent call last):
  File "dateconv.py", line 12, in <module>
    epoch = int(time.mktime(time.strptime(date_time, pattern)))
  File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '01-01-13' does not match format '%d-%m-%Y'

EDIT1:

感谢ajsp的回答,我改为:

#!/usr/bin/python

import time

with open('date.txt') as f:
    mylist = f.read().splitlines() 
    for date_time in mylist:
        if "/" in date_time:
            pattern = '%d/%m/%Y'
        else:
            pattern = '%d-%m-%y'
        epoch = int(time.mktime(time.strptime(date_time, pattern)))
        print epoch

但它仍然失败:

1356994800
1356994800
1356994800
1356994800
1367359200
1372629600
1372629600
1372629600
1380578400
1385852400
Traceback (most recent call last):
  File "dateconv.py", line 12, in <module>
    epoch = int(time.mktime(time.strptime(date_time, pattern)))
  File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
    (data_string, format))
ValueError: time data '1/19/2013' does not match format '%d/%m/%Y'

由于缺少前导0,因为文档说Month as a zero-padded decimal number

2 个答案:

答案 0 :(得分:2)

阅读datetime documentation

  

F将“年与世纪作为十进制数”匹配,例如2013年   %Y匹配“没有世纪的年份作为零填充十进制数”,例如13

试试这个,你真的应该付出更多努力!

%y

希望它有所帮助。

答案 1 :(得分:0)

最简单的方法是使用名为dateutil的第三方库,可以通过pip / easy_install进行安装 - 这可以节省您编写所有&#34;如何处理不同格式的日期&#34;逻辑自己。

from dateutil.parser import parse

for line in f.read().splitlines():
    dt = parse(line)
    print(dt, int(dt.timestamp()))

这给了你:

2013-01-01 00:00:00 1356998400
2013-01-12 00:00:00 1357948800
2013-01-19 00:00:00 1358553600
2013-01-21 00:00:00 1358726400
2013-01-21 00:00:00 1358726400
2013-01-30 00:00:00 1359504000
2013-02-01 00:00:00 1359676800
2013-02-02 00:00:00 1359763200
2013-02-12 00:00:00 1360627200
2013-02-13 00:00:00 1360713600
2013-02-23 00:00:00 1361577600

如果您不想使用第三方库,则不要使用strptime,而是提取组件并将其用作int代替datetime。这给出了与上面相同的结果:

from datetime import datetime
import re

for line in f.read().splitlines():
    m, d, y = map(int, re.split('[-/]', line))
    # use a more appropriate cut-off if needs be  
    # this assumes any two digit year is meant to be 2000
    if y < 100: 
        y += 2000
    dt = datetime(y, m, d)
    print(dt, int(dt.timestamp()))