【问题标题】:Convert a datetime.date() object with underscores rather than hyphens使用下划线而不是连字符转换 datetime.date() 对象
【发布时间】:2022-01-25 12:00:28
【问题描述】:

我正在尝试创建一个 datetime.date 对象,但将日期中的连字符更改为下划线。有没有办法用 datetime.date 对象做到这一点?还是我必须以某种方式对 datetime 对象执行此操作?

from datetime import datetime


date = datetime.strptime('2021-12-30', '%Y-%m-%d').date()

print(type(date))
# <class 'datetime.date'>
print(date)
# 2021-12-30

date_2 = date.strftime('%Y_%m_%d')
print(date_2)
# 2021_12_30
print(type(date_2))
# <class 'str'> I want this to stay as a datetime.date object

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    您所指的datetime 对象仅存在于这种形状中:datetime.date(2021, 12, 30)。当您在其上调用print() 时,它只是将其转换为字符串并打印出来:

    > print(date)
    2021-12-30
    

    也就是说,除非您决定使用字符串,否则不能使用下划线代替破折号。 strftime() 是将日期转换为字符串的好方法。否则,您可以使用以下内容获得相同的效果:

    > str(date).replace('-', '_')
    2021_12_30
    

    有关 Python 字符串和日期对象的更多颜色,请查看此答案:How to print a date in a regular format?

    【讨论】:

      【解决方案2】:

      第一个例子中的print(date)是由datetime处理的python datetime对象的字符串表示。str方法

      date.strftime 是根据给定格式获取字符串表示的函数

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-01
      相关资源
      最近更新 更多