说我有在以下五种方式之一格式化日期列表:更多Effecient方式格式化日期在Python中的MySQL
Date_Type_1 = 2001 Apr 15
Date_Type_2 = 2001 Apr
Date_Type_3 = 2000 Spring
Date_Type_4 = 2000 Nov-Dec
Date_Type_5 = 2001
所以,我的最新名单看起来是这样。
Date_list = ["2001 Apr 15", "2004 May 15", "2011 Jan", "2011 Fall", "2000 Nov-Dec", "2012", "2000 Spring" ]
我现在想尝试格式化这些日期,以便它们可以传递给MySQL数据库。我知道如何使用大量的条件流程。这是我如何做到这一点的一个例子。我不会包含所有条件,因为它会占用太多空间。
for i in Date_list:
year = i[:4]
#This will be my conditional logic to define a month.
#This is only an example. Will not include all 12 months, 4 seasons, and various bi-months
if "Apr" in i and "Mar-Apr" not in i:
month = 4
if "Mar-Apr" in i:
month = 3
if "May" in i and "May-Jun" not in i:
month = 5
if "Apr-May" in i:
month = 4
if "Spring" in i:
month = 3
#This will be conditional logic to define the day.
#I would do this for each of the 31 days of the month.
if "15" in i and "2015" not in i:
day = 15
date_return = datetime.datetime(year,month,day)
date_format = date_return.date().isoformat
问题在于我正在做出一些假设。我可以将季节定义为“春夏”,双月(例如三月/四月)作为特定月份返回。这个问题,至少在定义天数的时候是不会赶上日子的:
test_list = [2011 May, 2015 Apr 15]
for i in test_list:
if "15" in i and "2015" not in i:
day = 15
这不会赶上一天。我想知道是否有更有效的方法来做到这一点?目前的这种方法需要50个条件语句来定义日/月。
我不认为你的代码很慢,但看起来像你的高效率意味着更短的版本。 – YOU
这两个都是很好的答案,非常优雅。谢谢,我希望我可以选择两者。 – Sean