gpt4 book ai didi

python - 日期分类

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:01 25 4
gpt4 key购买 nike

我有一个 Excel 电子表格,正准备迁移到 Access,日期列包含多种格式的条目,例如:1963 年至 1969 年、1968 年 8 月至 1968 年 9 月、1972 年、3 月至 73 日、24 日至 7 月、 1980年10月2日、1980年8月29日、1946年7月等,并且“未注明日期”。我将作为键( map 编号)的列和日期列拉入 csv 并写回 csv。我可以去掉 4 位数的年份,但不能去掉范围。我很困惑如何提取需要手动重新格式化的天数和两位数年份。我的代码不是很优雅,可能不是最佳实践:

import csv, xlwt, re

# create new Excel document and add sheet
# from tempfile import TemporaryFile
from xlwt import Workbook
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')

# populate first row with header
sheet1.write(0,0,"Year")
sheet1.write(0,1,"Map")
sheet1.write(0,2,"As Entered")

# count variable for populating sheet
rowCount=0

# open csv file and read
with open('C:\dateTestMSDOs.csv', 'rb') as f:
reader=csv.reader(f)
for row in reader:

map = row[0] # first row is map number
dateRaw = row[1] # second row is raw date as entered

# write undated and blank entries
if dateRaw == 'undated':
yearStr = '0000'
rowCount +=1
sheet1.write(rowCount, 0, yearStr)
sheet1.write(rowCount, 1, map)
sheet1.write(rowCount, 2, dateRaw)
#print rowCount, yearStr, map, dateRaw, '\n'
yearStr=''

if dateRaw == '':
yearStr = 'NoEntry'
rowCount +=1
sheet1.write(rowCount, 0, yearStr)
sheet1.write(rowCount, 1, map)
sheet1.write(rowCount, 2, dateRaw)
#print rowCount, yearStr, map, dateRaw, '\n'
yearStr=''

# search and write instances of four consecutive digits
try:
year = re.search(r'\d\d\d\d', dateRaw)
yearStr= year.group()
#print yearStr, map, dateRaw
rowCount +=1
sheet1.write(rowCount, 0, yearStr)
sheet1.write(rowCount, 1, map)
sheet1.write(rowCount, 2, dateRaw)
#print rowCount, yearStr, map, dateRaw, '\n'
yearStr=''

# if none exist flag for cleaning spreadsheet and print
except:
#print 'Nope', map, dateRaw
rowCount +=1
yearStr='Format'
sheet1.write(rowCount, 0, yearStr)
sheet1.write(rowCount, 1, map)
sheet1.write(rowCount, 2, dateRaw)
#print rowCount, yearStr, map, dateRaw, '\n'
yearStr=''
yearStr=''
dateRaw=''

book.save('D:\dateProperty.xls')
print "Done!"

我想将日期和月份写入附加列,并提取范围条目的第二个 4 位数日期。

最佳答案

您可以尝试使用dateutil来实现此目的。我认为您仍然需要以不同的方式处理一些更困难的格式。请参阅下面的示例实现:

代码:

import dateutil.parser as dateparser

date_list = ['1963 to 1969',
'Aug. 1968 to Sept. 1968',
'Mar-73',
'24-Jul',
'Oct. 2 1980',
'Aug 29, 1980',
'July 1946',
'undated']

for d in date_list:
if 'to' in d:
a, b = d.split('to')
# Get the higher number. Use min to get lower of two.
print max(dateparser.parse(a.strip()).year, dateparser.parse(b.strip()).year)
elif d == 'undated':
print '0000'
else:
yr = dateparser.parse(d).year
print yr

结果:

1969
1968
1973
2014
1980
1980
1946
0000
[Finished in 0.4s]

我能看到的唯一明显的问题是 24-Jul 返回日期 2014 因为解析器假定当前的日、月或年来代替缺失的组件, IE。如果今天是本月 20 号,Mar-73 将变为 1973-03-20,等等。

关于python - 日期分类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com