【问题标题】:Split datetime into date and time将日期时间拆分为日期和时间
【发布时间】:2021-11-08 18:32:51
【问题描述】:

我必须以以下格式拆分日期时间以分隔变量 (日期,时间)

2015-11-31T13:45:00.000

注意:整个日期和时间存储在单个字符串变量中。

【问题讨论】:

标签: python


【解决方案1】:

始终使用日期库,以避免在您尝试自己做时可能发生的许多错误。在这种情况下,它看起来像 11 月 31 日,这不是一个有效的日子。

https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime

当然,您必须在格式方面提供帮助。我们将忽略 T,将其设为格式字符串中的文字。见What exactly does the T and Z mean in timestamp?

import datetime
format_string = "%Y-%m-%dT%H:%M:%S.%f"
date_string = "2015-11-31T13:45:00.000"
datetime.datetime.strptime(date_string, format_string)

builtins.ValueError: day is out of range for month

一旦你有了日期时间,用 strftime 打印出你想要的任何组件都会相对容易。当然,如果该文字始终存在,您可以只拆分“T”,但是您将不会真正拥有可靠的时间对象。它不会告诉您 11 月 31 日不是有效日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2022-06-14
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多