![](/img/trans.png)
[英]How to convert a date format (YYYY-MM-DD) to (YYYY,MM,DD) in Python
[英]Convert date format yyyy-m-d into yyyy-mm-dd on Python
在我的表中,我有不同類型的日期,只有數字和這兩種格式:
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
您可以使用python內置的datetime模塊
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
你可以試試:
>>> 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']
試試下面的代碼吧! 您必須導入日期時間文件。
輸入:
import datetime
date1 = datetime.datetime.strptime("2015-1-3", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)
today = datetime.date.today().strftime("%d-%m-%Y")
print(today)
輸出:
03-01-2015
17-01-2018
這有幫助
import datetime
d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d')
d.strftime('%Y-%m-%d')
這也應該有效:
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)
結果:
2001-01-01
2001-01-01
可能會有所幫助:
數據:
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']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.