5

したがって、UTC 時間の datetime オブジェクトがあり、それらを UTC タイムスタンプに変換したいと考えています。問題は、time.mktime がローカルタイムを調整することです。

だからここにいくつかのコードがあります:

import os
import pytz
import time
import datetime

epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
print time.mktime(epoch.timetuple())

os.environ['TZ'] = 'UTC+0'
time.tzset()
print time.mktime(epoch.timetuple())

ここにいくつかの出力があります:

Python 2.6.4 (r264:75706, Dec 25 2009, 08:52:16) 
[GCC 4.2.1 (Apple Inc. build 5646) (dot 1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> import pytz
>>> import time
>>> import datetime
>>> 
>>> epoch = pytz.utc.localize(datetime.datetime(1970, 1, 1))
>>> print time.mktime(epoch.timetuple())
25200.0
>>> 
>>> os.environ['TZ'] = 'UTC+0'
>>> time.tzset()
>>> print time.mktime(epoch.timetuple())
0.0

したがって、明らかにシステムが UTC 時間であれば問題ありませんが、そうでない場合は問題になります。環境変数の設定と time.tzset の呼び出しは機能しますが、安全ですか? システム全体で調整したくありません。

これを行う別の方法はありますか?または、この方法で time.tzset を呼び出しても安全ですか。

4

1 に答える 1

6

The calendar module contains calendar.timegm which solves this problem.

calendar.timegm(tuple)

An unrelated but handy function that takes a time tuple such as returned by the gmtime() function in the time module, and returns the corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, time.gmtime() and timegm() are each others’ inverse.

于 2010-07-23T03:03:47.593 に答える