如何使用Python来计算时间 [英] How to use Python to calculate time
问题描述
我想编写作为时间计算器的python脚本。
I want to write python script that acts as a time calculator.
例如:
假设现在时间是13:05:00
Suppose the time is now 13:05:00
我想添加1小时23分10秒。
I want to add 1 hour, 23 minutes, and 10 seconds to it.
,我想打印答案。
如何在Python中执行此操作?
How do I do this in Python?
如果日期也涉及到b $ b
What if date is also involved?
推荐答案
datetime.timedelta
是为固定时间差异设计的(例如1天是固定的,1个月不是)。
datetime.timedelta
is designed for fixed time differences (e.g. 1 day is fixed, 1 month is not).
>>> import datetime
>>> t = datetime.time(13, 5)
>>> print t
13:05:00
>>> now = datetime.datetime.now()
>>> print now
2009-11-17 13:03:02.227375
>>> print now + datetime.timedelta(hours=1, minutes=23, seconds=10)
2009-11-17 14:26:12.227375
请注意,在一段时间内进行添加并不合适(但您可以将日期和时间组合成一个datetime对象,使用它,然后获取时间)。 DST是主要的罪魁祸首。例如,12:01 am + 5小时可以是4:01 am,5:01 am或6:01 am在不同的日子。
Note that it doesn't make sense to do addition on just a time (but you can combine a date and a time into a datetime object, use that, and then get the time). DST is the major culprit. For example, 12:01am + 5 hours could be 4:01am, 5:01am, or 6:01am on different days.
这篇关于如何使用Python来计算时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!