【发布时间】:2015-05-20 22:19:19
【问题描述】:
假设您有一个datetime.date 对象,例如datetime.date.today() 返回的对象。
然后你还会得到一个字符串,表示与日期对象互补的时间。
在 datetime.datetime 对象中结合这两者的 Python 方式是什么?更具体地说,我可以避免将日期对象转换为字符串吗?
这就是我现在完成它的方式:
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'
【问题讨论】:
-
你如何获得
time_str? -
@PascalvKooten:来自 sar 的输出
-
注意:
time.strptime(*args)返回time.struct_time(),而不是datetime.time()。要获得后者,请致电datetime.strptime(*args).time()。 -
@J.F.Sebastian 非常完美,这是拼图的最后一块(对于我来说,在这个特殊的例子中,我所有的借口都是用户 abarnert 没有阅读完整的 datetime.datetime/datetime.date/datetime。 time/time.struc_time/etc 文档并冒险提出关于 SO 的问题,因此按照这种思路,也许是时候人们通过阅读文档和书籍而不是打扰其他 SO 用户来自己整理东西了。 .. )