python日期str解析

时间:2021-06-26 10:48:02

标签: python python-3.x

我有一些字符串日期 我尝试计算从今天到字符串日有多少天 示例字符串日期

examples=["June 30 - July 16","Thursday, July 15","July 9 - 19"]

我只写一种类型

import datetime
arriveTimes="June 30 - July 16"
dates=arriveTimes.split(" - ")
monthToNumber = {
'January' : 1,         
'February' : 2,         
'March' : 3,           
'April' : 4,              
'May' : 5, 
'June' : 6,
'July' : 7, 
'August' : 8, 
'September' : 9, 
'October' : 10, 
'November' : 11, 
'December' : 12}
firstMounth=""
arriveTimesOnDayList=[]
for date in dates:
    
    month,day=date.split(" ")
    
    
    month=str([v for k, v in monthToNumber.items() if month.lower() in k.lower()][0])
    today = datetime.datetime.now()
    year=str(today.year)
    dateTimeObj = datetime.datetime.strptime(year+"-"+month+"-"+day, '%Y-%m-%d')
    arriveTimeDatetimeObj = dateTimeObj - today
    arriveTimesOnDayList.append(str(arriveTimeDatetimeObj.days))
print(arriveTimesOnDayList)
arriveTimesOnDayStr=arriveTimesOnDayList[0]+"-"+arriveTimesOnDayList[1]
print(arriveTimesOnDayStr)

但我希望它支持所有类型

1 个答案:

答案 0 :(得分:1)

datetime 没有解析任意日期字符串的功能,您可能需要找到一些这样做的库。

datetime.strptime() 需要固定格式,因此您需要将所有日期字符串保持为相同格式,或者您可能需要列出您想要的所有格式,然后一一尝试。

from datetime import datetime
def get_date(date):
    # %B for month full name, %A for weekday full name
    formats = ["%B %d", "%A, %B %d", "%d"]
    today = datetime.now()
    for f in formats:
        try:
            dt = datetime.strptime(f"{today.year} {date}", f"%Y {f}")
            # if the date is before today, treated as date in next month
            if dt < today:
                dt = dt.replace(month=today.month+1)
            return dt
        except ValueError:
            continue
    else:
        print("Date format not supported.")

def day_from_today(dates):
    for date in dates:
        dt = get_date(date)
        if dt:
            dft = (dt - datetime.now()).days
            print(f"{dft} {'days' if dft > 1 else 'day'} to {dt.date()}")

example = ["June 30", "July 16", "Thursday, July 15", "June 28", "19", "7 19"]
day_from_today(example)

结果:

2 days to 2021-06-30
18 days to 2021-07-16
17 days to 2021-07-15
0 day to 2021-06-28
21 days to 2021-07-19
Date format not supported.