【问题标题】:displaying a date in a particular format in python [duplicate]在python中以特定格式显示日期[重复]
【发布时间】:2019-05-05 19:02:56
【问题描述】:
from datetime import date
today = dt.datetime.today().date()

todays_file = 'C:\\Temp\\'+str(today.year)+str(today.month)+str(today.day)+str('.csv')

跑步:

todays_file

给予:

'C:\\Temp\\2018124.csv'

但是 - 我需要它的格式为 yyyymmdd(不是 yyyymmd)

所以预期的输出是:

'C:\\Temp\\20181204.csv'

同样,2019 年 2 月 3 日的预期产出是:

'C:\\Temp\\20190203.csv'

有没有不使用 if len(today.day or today.month) = 1: 等的聪明方法

【问题讨论】:

    标签: python datetime


    【解决方案1】:
    from datetime import date
    today_str = date.today().strftime('%Y%m%d')
    file_name = '{}.csv'.format(today_str)
    # or in python 3.6+
    file_name = f'{today_str}.csv'
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      d = datetime.datetime.now()
      todays_file = 'C:\\Temp\\' + str(d.year) + str("%02d"%d.month) + str("%02d"%d.day) + '.csv'
      

      给:

      'C:\\Temp\\20181204.csv'
      

      【讨论】:

        【解决方案3】:

        使用.strftime("%Y%m%d")

        例如:

        import datetime
        today = datetime.datetime.today().date()
        
        todays_file = r'C:\\Temp\\{}.csv'.format(today.strftime("%Y%m%d"))    
        print(todays_file)
        

        输出:

        C:\\Temp\\20181204.csv
        

        您也可以使用str.formatfstring 来形成所需的结果字符串。

        【讨论】:

          猜你喜欢
          • 2018-04-15
          • 1970-01-01
          • 2015-08-06
          • 2018-01-13
          • 1970-01-01
          • 1970-01-01
          • 2017-06-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多