在我的表格中,我有不同类型的日期,只有数字和两种格式:
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
答案 0 :(得分:4)
您可以使用内嵌的 datetime module
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
答案 1 :(得分:1)
您可以尝试:
>>> d = "2018-1-1"
>>> d_list = d.split("-")
>>> d_list
['2018', '1', '1']
>>> if len(d_list[1]) < 2:
d_list[1] = "0"+d_list[1]
>>> if len(d_list[2]) < 2:
d_list[2] = "0"+d_list[2]
>>> d_list
['2018', '01', '01']
答案 2 :(得分:1)
尝试以下代码! 您必须导入日期时间文件。
输入:
03-01-2015
17-01-2018
输出
$string = "1\n2\n3\n4\n\n\n";
答案 3 :(得分:1)
这有助于
import datetime
d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d')
d.strftime('%Y-%m-%d')
答案 4 :(得分:1)
这也应该有效:
kerasImage = kerasImage.transpose(1,2,0)
结果:
from datetime import datetime
d1 = "2001-1-1"
d2 = "2001-01-01"
d1 = datetime.strptime(d1, '%Y-%m-%d')
d1 = d1.strftime('%Y-%m-%d')
print(d1)
d2 = datetime.strptime(d2, '%Y-%m-%d')
d2 = d2.strftime('%Y-%m-%d')
print(d2)
答案 5 :(得分:0)
可能会有所帮助:
数据:强>
de = ["2018-1-1", "2018-02-1", "2017-3-29"]
<强>功能:强>
from datetime import datetime
def format_date(d):
"""Format string representing date to format YYYY-MM-DD"""
dl = d.split("-")
return '{:%Y-%m-%d}'.format(datetime(int(dl[0]),int(dl[1]),int(dl[2])))
print([format_date(i) for i in de])
<强>结果:强>
['2018-1-1', '2018-02-1', '2017-3-29']