繁体   English   中英

在Python上将日期格式yyyy-md转换为yyyy-mm-dd

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM