如何将`datetime.time`转换为`datetime.datetime`?

huangapple go评论67阅读模式
英文:

How to convert datetime.time to datetime.datetime?

问题

Error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

我正在尝试减去两个时间,它们都是以datetime.time格式。如何在Python中将它们转换为datetime.datetime。

我有一个问题,需要一个解决方法来编写我的代码。

英文:

I am trying to subtract 2 times and they both are in datetime.time format. How to convert them to datetime.datetime in python.

> Error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I have a question to which I need a workaround to write my code.

答案1

得分: 0

import datetime

time1 = datetime.time(1, 0, 0)
time2 = datetime.time(1, 30, 0)

today = datetime.date.today()

datetime1 = datetime.datetime.combine(today, time1)
datetime2 = datetime.datetime.combine(today, time2)

time_diff = datetime2 - datetime1

# 结果是一个 timedelta 对象
print(time_diff)
英文:
import datetime

time1 = datetime.time(1, 0, 0)
time2 = datetime.time(1, 30, 0)

today = datetime.date.today()

datetime1 = datetime.datetime.combine(today, time1)
datetime2 = datetime.datetime.combine(today, time2)

time_diff = datetime2 - datetime1

# The result is a timedelta object
print(time_diff)

You may use a common datetime, here today, and then subtract them

答案2

得分: 0

你可以使用datetime.combine()函数,但是要注意,这种方法存在潜在的问题。

import datetime
t1 = datetime.time(8)  # 上午8点
t2 = datetime.time(17)  # 下午5点
d = datetime.date(2000, 1, 1)  # 任意日期
delta = datetime.datetime.combine(d, t2) - datetime.datetime.combine(d, t1)
print(delta)

打印结果:

<pre>
datetime.timedelta(seconds=32400)
</pre>

潜在的问题:

  • 不考虑夏令时

  • 1点减去11点晚上得到的是22小时,这可能不是你想要的

  • 请注意,如果time对象中包含tzinfo,它将被继承到datetime对象中,这可能是你想要的,也可能不是。

英文:

You can use the datetime.combine() function BUT!! be aware that there are potential pitfalls to this approach.

import datetime
t1 = datetime.time(8)  # 8:00 AM
t2 = datetime.time(17) # 5:00 PM
d = datetime.date(2000, 1, 1) # Arbitrary date
delta = datetime.datetime.combine(d, t2) - datetime.datetime.combine(d, t1)
print(delta)

Prints:

<pre>
datetime.timedelta(seconds=32400)
</pre>

Potential pitfalls:

  • Does not account for daylight savings

  • 1AM minus 11PM is negative 22 hours, that may not be what you want

  • Note that if the tzinfo is present in the time object, it will be inherited by the datetime object—this may or may not be what you want

huangapple
  • 本文由 发表于 2023年2月16日 05:13:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定