我正在尝试将现有日期从March 02, 2019 6:30 - 11:00 pm
转换为3/2/19
格式,但是我不知道该怎么做。
这些是日期:
datelist = [
"March 02, 2019 6:30 - 11:00 pm",
"June 21, 2019",
"March 22, 2019 5:00 - 10:00 pm",
"May 01, 2019 - June 15, 2019 11:59 pm",
"May 02, 2019 5:30 - 8:00 pm",
"May 04, 2019 5:00 - 10:30 pm",
"September 08, 2018 6:00 - 10:00 pm",
]
for date in datelist:
print(date)
预期输出:
3/2/2019
6/21/2019
3/22/2019
5/1/2019 - 6/15/2019
5/2/2019
5/4/2019
9/8/2018
这是我能找到的最接近的
import datetime
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = datetime.datetime.strptime(date_time_str, '%b %d %Y %I:%M%p').strftime('%m/%d/%Y')
print(date_time_obj)
但是,当列表中的日期类型不同时,这实际上并没有达到目的。
如何将日期转换为所需格式?
答案 0 :(得分:3)
我喜欢使用模块dateutil
,因为它在内部尝试对传入的日期格式进行有根据的猜测:
from dateutil import parser as dateparser
date_time_str = 'Jun 28 2018 7:40AM'
date_time_obj = dateparser.parse(date_time_str)
print(date_time_obj.strftime('%m/%d/%Y'))
它似乎很健壮。
答案 1 :(得分:2)
您还可以使用正则表达式查找日期,然后使用datetime和strftime转换为日期时间,以所需的格式表示:
import re
import datetime
datelist = [
"March 02, 2019 6:30 - 11:00 pm",
"June 21, 2019",
"March 22, 2019 5:00 - 10:00 pm",
"May 01, 2019 - June 15, 2019 11:59 pm",
"May 02, 2019 5:30 - 8:00 pm",
"May 04, 2019 5:00 - 10:30 pm",
"September 08, 2018 6:00 - 10:00 pm",
]
find_dates = re.compile(r'((?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{2},\s\d{4})')
new_dates = [re.findall(find_dates, x) for x in datelist]
datetime_dates = []
for x in new_dates:
dts = []
for y in x:
dt = datetime.datetime.strptime(y, '%B %d, %Y')
dts.append(dt.strftime("%m/%d/%Y"))
datetime_dates.append('-'.join(dts))
print(datetime_dates)
输出:
['03/02/2019',
'06/21/2019',
'03/22/2019',
'05/01/2019-06/15/2019',
'05/02/2019',
'05/04/2019',
'09/08/2018']
答案 2 :(得分:0)
使用my_date = datetime.strptime("June 21, 2019","%B %d, %Y")
将输入格式转换为日期时间。下次以所需格式打印:my_date.strftime("%m/%d/%Y")
输入时间:“ 2019年6月21日”,结果:“ 06/21/2019”
此网站提供全面的指南: https://stackabuse.com/how-to-format-dates-in-python/
答案 3 :(得分:0)
以下代码为您提供了与查找完全相同的输出,可以处理一行中有多个日期的情况:
datelist = [
"March 02, 2019 6:30 - 11:00 pm",
"June 21, 2019",
"March 22, 2019 5:00 - 10:00 pm",
"May 01, 2019 - June 15, 2019 11:59 pm",
"May 02, 2019 5:30 - 8:00 pm",
"May 04, 2019 5:00 - 10:30 pm",
"September 08, 2018 6:00 - 10:00 pm",
]
import datetime
def parse(x):
p = ""
for format_ in ['%B %d, %Y %H:%M', '%B %d, %Y', '%B %d, %Y %H:%M %p']:
try:
p = datetime.datetime.strptime(x.strip(), format_)
except ValueError:
continue
return p
def format_(x):
if type(x) == str:
return x
return x.strftime("%-m/%-d/%Y")
final_dates = []
for dates in datelist:
final_string = []
for date in dates.split(" - "):
date = parse(date)
date = format_(date)
if len(date):
final_string.append(date)
final_dates.append("-".join(final_string))
Out[218]:
['3/2/2019',
'6/21/2019',
'3/22/2019',
'5/1/2019 - 6/15/2019',
'5/2/2019',
'5/4/2019',
'9/8/2018']