【问题标题】:Converting string to date object without time info将字符串转换为没有时间信息的日期对象
【发布时间】:2014-06-13 00:09:24
【问题描述】:

我想将字符串转换为 Python 日期对象。根据https://docs.python.org/2/library/datetime.html 上的文档,我正在使用d = datetime.strptime("25-01-1973", "%d-%m-%Y"),这会产生datetime.datetime(1973, 1, 25, 0, 0)

当我使用d.isoformat() 时,我得到'1973-01-25T00:00:00',但我想根据文档获得1973-01-25(没有时间信息):

date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example, date(2002, 12, 4).isoformat() == '2002-12-04'.

据了解,我可以使用 SimpleDateFormat 等,但由于文档中明确提到了 isoformat() 示例,我不确定为什么会在日期之后收到不需要的时间信息。

我想我在某处遗漏了一个细节?

【问题讨论】:

    标签: python


    【解决方案1】:

    datetime.datetime.strptime 返回的对象是datetime.datetime 对象,而不是datetime.date 对象。因此,它将包含时间信息,并且在调用 isoformat() 时将包含此信息。

    您可以使用datetime.datetime.date() 方法将其转换为date 对象,如下所示。

    import datetime as dt
    
    d = dt.datetime.strptime("25-01-1973", "%d-%m-%Y")
    
    # Convert datetime object to date object.
    d = d.date()
    
    print(d.isoformat())
    # 1973-01-25
    

    【讨论】:

    • 有问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-12-13
    • 2021-08-06
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多