【问题标题】:Combine datetime.date object with time string in a datetime.datetime object将 datetime.date 对象与 datetime.datetime 对象中的时间字符串结合起来
【发布时间】: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 用户来自己整理东西了。 .. )

标签: python datetime


【解决方案1】:

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

类方法 datetime.combine(date, time)

返回一个新的datetime 对象,其日期分量等于给定date 对象,其时间分量和tzinfo 属性等于给定time 对象。对于任何datetime 对象dd == datetime.combine(d.date(), d.timetz())。如果 datedatetime 对象,则忽略其时间组件和 tzinfo 属性。

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

当然,您需要将 time_str 解析为 time 对象,但您显然已经知道该怎么做。


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2010-09-25
    • 2012-06-26
    • 2021-06-03
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多