英文:
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 thetime
object, it will be inherited by thedatetime
object—this may or may not be what you want
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论