[英]Python - Add leading zeros to digits in date in CSV file
在Win8上使用Python 3.3。 我認為自己是腳本編寫的新手。 我正在嘗試使用沒有前導零的Excel電子表格中的日期。 年份末尾總是2位數字,月份排在第一位,然后中間是一天。 我可以提取Excel列以將其單獨放置在文件中。 以下是一些示例,這些示例可能涉及數千行內容,並將日期固定為可識別的格式:
1188(問題)11188(問題日期)12188(問題日期)13188(mddyy)21188(mddyy)111188(mmddyy)
我想我的問題分為兩部分:(1)使用Python修改時最容易使用哪種類型的文件(例如XLSX,XLS,CSV,TXT等)(2)使用以下代碼編碼的任何技巧Python ...也許要使用的功能?
以下是我想應用的邏輯,因為我知道無法真正判斷日期是否只有5位數字並以“ 11”或“ 12”開頭,因此我想放置ERROR以便我們返回手動修復這些問題。 這個想法是更少的體力勞動,更好。
我的旅程
最終代碼如下!
import csv
# Change to location of CSV file
with open('c:\\Users\\Weez\\Desktop\\csv_test.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
baddate = line[0]
year = int(baddate) % 100
md = int(baddate) // 100
# Check year values
if year < 10:
year = str(200)+str(year)
elif year <= 50:
year = str(20)+str(year)
else:
year = str(19)+str(year)
# Check month and day values
if md < 100:
month = md // 10
month = str(month).zfill(2)
day = md % 10
day = str(day).zfill(2)
elif md >= 1000:
pass
elif md <= 109:
month = md // 10
day = md % 10
day = str(day).zfill(2)
elif md == 110:
month = md // 100
month = str(month).zfill(2)
day = md % 100
elif md == 120:
month = md // 100
month = str(month).zfill(2)
day = md % 100
elif md <= 129:
month = str("XX")
day = str("XX")
else:
month = md // 100
month = str(month).zfill(2)
day = md % 100
dateresult = str(month)+str(day)+str(year)
print(dateresult)
# modes 'a' = append, 'w' = write, 'r' = read and other modes
with open('c:\\Users\\Weez\\Desktop\\csv_test_output.csv', 'a') as csvoutput:
csvoutput.write(dateresult)
csvoutput.write('\n')
print('\n')
print('\n')
str(input("Process complete! Press Enter to finish!"))
對於#1,您可以使用csv
盡管我對其他模塊沒有任何經驗:(。
對於#2,您可以使用內置模塊datetime
>>> from datetime import datetime
>>> date_unpadded_month = '1188'
>>> date_padded_month = '01188'
>>> date_2_digit_month = '11188'
>>> date_format = '%m%d%y'
>>> parsed = datetime.strptime(date_unpadded_month, date_format)
>>> parsed
>>> datetime.datetime(1988, 1, 1, 0, 0)
>>> parsed = datetime.strptime(date_padded_month, date_format)
>>> parsed
>>> datetime.datetime(1988, 1, 1, 0, 0)
>>> parsed = datetime.strptime(date_2_digit_month, date_format)
>>> parsed
>>> datetime.datetime(1988, 11, 1, 0, 0)
>>> parsed.month
>>> 11
如果電子表格中的日期正確無誤,則可以追溯回去並修復以前含糊不清的日期,並獲得很高的成功。 例如,如果您有
123087, 11188, 22288
第一個和最后一個日期是明確的( Dec-30-'87
& Feb-22-'88
),中間日期是Jan-11-'88
或Jan-11-'88
Nov-1-'88
,但是如果您知道三個日期是按順序排列的。
編輯:這是實現此目的的一些代碼:
from datetime import datetime
data = '123087', '1188', '11188', '22288', '11188' # some 4, 5 and 6 digit dates
fmt = '%m%d%y'
results = []
# parse possible dates from data
for date_str in data:
alt_date_str = ('0' + date_str)[-6:]
dates = (datetime.strptime(d, fmt) for d in (date_str, alt_date_str))
results.append(set(dates)) # make sure dates are unique
# iterate through results, removing anything older than the previous entries
oldest = datetime.min
for i in xrange(len(results)):
results[i] = [d for d in results[i] if d > oldest]
oldest = min(results[i])
# iterate backwards, removing anything newer than the previous entries
newest = datetime.max
for i in reversed(xrange(len(results))):
results[i] = [d for d in results[i] if d < newest]
newest = max(results[i])
# show dates, error if still ambiguous
for dates in results:
if len(dates) > 1:
print 'ERROR:', dates
else:
print dates[0]
由於年份始終是兩位數,因此您可以立即消除那部分問題。
year = date % 100
md = date // 100
現在,您可以消除2位數和4位數的情況:
if md < 100:
month = md / 10
day = md % 10
elif md >= 1000:
month = md / 100
day = md % 100
現在您可以檢測潛在的問題區域並解決歧義。
elif md <= 109:
month = 10
day = md % 10
elif md == 110:
month = 1
day = 10
elif md <= 129:
month = None # ambiguous
day = None
else:
month = md / 100
day = md % 100
您需要做一些額外的檢查,以確保月份和日期在范圍之內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.