22

我想从 Python 获取 UTC 文件的修改日期。以下代码返回我的 Linux 配置时区 (GMT-5) 中的日期。我想要它在UTC。或者我如何获得 os 配置的时区以将其转换为 pytz ?

$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> import os
>>> dt=os.path.getmtime('/home/user/.bashrc')
>>> datetime.datetime.fromtimestamp(dt)
datetime(2012, 5, 30, 21, 18, 10)

谢谢

4

2 回答 2

36

试试datetime.datetime.utcfromtimestamp

import datetime
import os
dt=os.path.getmtime('/home/me/.bashrc')
print (datetime.datetime.fromtimestamp(dt))
print (datetime.datetime.utcfromtimestamp(dt))
于 2012-07-10T00:28:19.080 回答
1

使用您当地的时区代替“America/New_York”,以下应该可以解决问题。

In [11]: import datetime, pytz

In [12]: right_now = datetime.datetime.now()

In [13]: right_now_utc = right_now.replace(tzinfo=pytz.timezone("America/New_York")).astimezone(pytz.utc)

In [14]: right_now
Out[14]: datetime.datetime(2012, 7, 9, 20, 31, 21, 999536)

In [15]: right_now_utc
Out[15]: datetime.datetime(2012, 7, 10, 1, 31, 21, 999536, tzinfo=<UTC>)
于 2012-07-10T00:33:11.733 回答