假设您有一个 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
datetimeobject whose date components are equal to the givendateobject’s, and whose time components andtzinfoattributes are equal to the giventimeobject’s. For anydatetimeobject d,d == datetime.combine(d.date(), d.timetz()). If date is adatetimeobject, its time components andtzinfoattributes are ignored.
因此,您不必自己编写方法;它已经存在于模块中。
当然,您需要将 time_str 解析为 time 对象,但您显然已经知道如何执行此操作。
但是,如果您确实想自己编写它,那么将日期和时间格式化为字符串只是为了将它们解析出来是很愚蠢的。为什么不直接访问属性?
return datetime(d.year, d.month, d.day, t.hour, t.minute. t.second, t.tzinfo)
