日期时间和时间

2024-05-19 02:25:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的时区是UTC+5。

所以当我做datetime.datetime.now()时,它给出:

2012-07-14 06:11:47.318000
#note its 6AM

我想从中减去5小时,使之等于datetime.datetime.utcnow()所以我做了:

import time
from datetime import datetime, timedelta
dt = datetime.now() - timedelta(hours=time.timezone/60/60)
print dt
#gives 2012-07-14 11:11:47.319000

"""
Here 11 is not the PM its AM i double check it by doing
print dt.strftime('%H:%M:%S %p')
#gives 11:11:47 AM
"""

你看,不是减去5个小时,而是在日期时间上加5个小时?? 我在这里做错什么了吗?


Tags: fromimportdatetimetimedtamnowtimedelta
2条回答

The documentation很清楚:

time.timezone The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).

所以正的UTC值有一个负时区。

你在创造一个负时间差。time.timezone的值为负:

>>> import time
>>> time.timezone
-36000

这里,我是UTC+10,所以您的代码变成:

>>> from datetime import timedelta
>>> print timedelta(hours=time.timezone/60/60)
-1 day, 14:00:00

相关问题 更多 >

    热门问题