在我的表中,我有不同类型的日期,只有数字和这两种格式:
yyyy-m-d
yyyy-mm-dd
例如,月份中的某些值在10个月以下的情况下不具有零,我需要它创建条件以在最新日期之前选择元素.
我希望所有这些都具有相同的格式:
yyyy-mm-dd
任何pythonic方式来解决这个问题?
目前我正在使用这个:
if line.startswith('# Date: '):
#date = 2014-5-28
d = line.strip().split(':')[-1].split('-').replace(' ','')
if len(d[0]) == 4:
year = str(d[0])
elif len(d[1]) < 2:
month = '0'+ str(d[1])
elif len(d[2]< 2):
day = '0'+ str(d[1])
date = year + month + day
最佳答案 你可以使用内置的
datetime module python
import datetime
date1 = "2018-1-1"
date2 = "2018-01-01"
datetime_object = datetime.datetime.strptime(date1, "%Y-%m-%d")
datetime_object2 = datetime.datetime.strptime(date2, "%Y-%m-%d")
print datetime_object.strftime("%Y-%m-%d")
print datetime_object2.strftime("%Y-%m-%d")
结果:
2018-01-01
2018-01-01