gpt4 book ai didi

python - 将 datetime.date 对象与 datetime.datetime 对象中的时间字符串组合

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:52 29 4
gpt4 key购买 nike

假设您有一个 datetime.date 对象,例如 datetime.date.today() 返回的对象。

稍后您还会得到一个表示时间的字符串,它补充了日期对象。

在 datetime.datetime 对象中结合这两者的 pythonic 方法是什么?更具体地说,我可以避免将日期对象转换为字符串吗?

目前我是这样完成的:

def combine_date_obj_and_time_str(date_obj, time_str):
# time_str has this form: 03:40:01 PM
return datetime.datetime.strptime(date_obj.strftime("%Y-%m-%d") + ' ' + time_str, "%Y-%m-%d %I:%M:%S %p")

编辑:

我按照第一个答案的描述查看了 datetime.datetime.combine,但我对将时间字符串放入时间对象有点不知所措:

>>> datetime.datetime.combine(datetime.date.today(), time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: combine() argument 2 must be datetime.time, not time.struct_time
>>> datetime.datetime.combine(datetime.date.today(), datetime.time.strptime("03:40:01 PM", "%I:%M:%S %p"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'strptime'

最佳答案

如果您只是阅读 datetime 的文档,或查看交互式解释器中的 help(datetime),您将看到 combine方法:

classmethod datetime.combine(date, time)

Return a new datetime object whose date components are equal to the given date object’s, and whose time components and tzinfo attributes are equal to the given time object’s. For any datetime object d, d == datetime.combine(d.date(), d.timetz()). If date is a datetime object, its time components and tzinfo attributes are ignored.

因此,您不必自己编写方法;它已经存在于模块中。

当然,您需要将 time_str 解析为 time 对象,但您显然已经知道如何执行此操作。


但是,如果您确实想自己编写它,那么将日期和时间格式化为字符串只是为了将它们解析出来是很愚蠢的。为什么不直接访问属性?

return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)

关于python - 将 datetime.date 对象与 datetime.datetime 对象中的时间字符串组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361349/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com