如果我不知道datetime是否是偏移感知的,那么如何减去offset-naive和offset-aware datetime?

时间:2017-03-27 09:39:30

标签: python timezone

我很难处理时区。有人可以给我一些建议吗?

目前尚不清楚'lastday'是否具有偏移感知能力。在这种情况下,我怎样才能减去两次'lastday'和'today'?

假设'lastday'是偏移感知的, 通过执行以下代码:

lastday = snapshotinfo.dateCreated
print 'lastday:',lastday
today = datetime.datetime.today()
print 'today:',today
today = pytz.utc.localize(today)
print 'today after localize:',today
diff = abs(today - lastday).days
print 'diff:', diff

我可以得到以下结果

lastday: 2017-03-27 00:24:16.295000+09:00
today: 2017-03-27 18:23:41.284000
today after localize: 2017-03-27 18:23:41.284000+00:00
diff: 1

但是在另一台服务器上,'lastday'是偏向天真的。在这种情况下,我收到以下错误:

lastday: 2017-03-27 00:23:21.000215
today: 2017-03-27 18:33:34.883176
today after localize: 2017-03-27 18:33:34.883176+00:00
diff = abs(today - lastday).days
TypeError: can't subtract offset-naive and offset-aware datetimes

我怎么知道'lastday'是否偏向天真?如果我能够知道,我想我可以决定是否转换'今天'。

0 个答案:

没有答案