[英]Convert date format yyyy-m-d into yyyy-mm-dd on Python
In my table, I have different types of dates just with numbers and in this two formats: 在我的表中,我有不同类型的日期,只有数字和这两种格式:
yyyy-m-d
yyyy-mm-dd
Some values, as the month for example, don't have the zero in the case of months under 10 and I need it to create a condition to chose elements by the latest date. 例如,月份中的某些值在10个月以下的情况下不具有零,我需要它创建条件以在最新日期之前选择元素。
I want that all of them have the same format: 我希望所有这些都具有相同的格式:
yyyy-mm-dd
Any pythonic way to solve that? 任何pythonic方式来解决这个问题?
For the moment I am using this: 目前我正在使用这个:
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
You can use the python inbuilt datetime module 您可以使用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")
Result: 结果:
2018-01-01
2018-01-01
You can try: 你可以试试:
>>> 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']
Try the below code ! 试试下面的代码吧! You have to import the date time file .
您必须导入日期时间文件。
Input : 输入:
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)
Output : 输出:
03-01-2015
17-01-2018
This helps 这有帮助
import datetime
d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d')
d.strftime('%Y-%m-%d')
This should work as well: 这也应该有效:
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)
Results: 结果:
2001-01-01
2001-01-01
May be this will help: 可能会有所帮助:
Data: 数据:
de = ["2018-1-1", "2018-02-1", "2017-3-29"]
Function: 功能:
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])
Result: 结果:
['2018-1-1', '2018-02-1', '2017-3-29']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.