我有日期已混合的格式一樣的列表:將字符串轉換日期與混合格式劃時代
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
...
我想這個列表轉化爲劃時代的列表(以保持它在SQLite的分貝在Android)。所以我寫了一個腳本(基於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'
[email protected]:~/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
。
它不起作用,因爲您沒有按照正確順序的日 - 月 - 年方向。你不可能有19個月,因爲一年只有12個。複製並粘貼下面的代碼,它與您提供的樣本數據一起工作。 – ajsp
@ajsp這不是19個月,它是1月19日。 –
嘗試將問題限制爲單個問題(您的第一個問題是%Y - >%y,第二個問題%d /%m - >%m /%d)。儘管[@ ajsp的回答](http://stackoverflow.com/a/33209275/4279)修復了這兩個問題。 – jfs