【问题标题】:Convert date format yyyy-m-d into yyyy-mm-dd on Python在 Python 上将日期格式 yyyy-m-d 转换为 yyyy-mm-dd
【发布时间】:2018-01-17 10:23:53
【问题描述】:

在我的表格中,我有不同类型的日期,只有数字和这两种格式:

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 date date-format


【解决方案1】:

你可以使用python内置的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

【讨论】:

  • 你知道它为什么起作用吗:reldate = datetime.datetime.strptime(d, "%Y-%m-%d") print reldate .strftime("%Y-%m-%d") 而不是:day = reldate.strptime("%Y-%m-%d") 错误:day = str(reldate.strptime("%Y-%m-%d")) TypeError: strptime() 只需要 2 个参数(给定 1 个)
  • @F.Lira。 'strptime' 方法需要 2 个参数。字符串和日期时间格式。例如:datetime.datetime.strptime(date1, "%Y-%m-%d")
  • 我解决了这个问题:reldate = (datetime.datetime.strptime(d, "%Y-%m-%d")).strftime("%Y-%m-%d") \day = reldate.replace('-', '')
  • 仅供参考:如果您不想要'-',您可以直接在 strftime 中删除它,例如 datetime_object.strftime("%Y%m%d")。
【解决方案2】:

试试下面的代码! 您必须导入日期时间文件。

输入:

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

【讨论】:

    【解决方案3】:

    你可以试试:

    >>> 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']
    

    【讨论】:

      【解决方案4】:

      这有帮助

      import datetime    
      d = datetime.datetime.strptime('2014-5-28', '%Y-%m-%d')
      d.strftime('%Y-%m-%d')
      

      【讨论】:

        【解决方案5】:

        这应该也可以:

        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
        

        【讨论】:

          【解决方案6】:

          这可能会有所帮助:

          数据:

          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']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-06-24
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            相关资源
            最近更新 更多