2012-07-10 126 views
15

我想從Python獲取UTC格式文件的修改日期。以下代碼返回Linux配置時區(GMT-5)中的日期。我需要它在UTC。或者我如何獲得os配置的時區來使用pytz轉換它?如何從Python獲取UTC格式的文件修改日期

$ 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) 

感謝

回答

20

嘗試datetime.datetime.utcfromtimestamp

import datetime 
import os 
dt=os.path.getmtime('/home/me/.bashrc') 
print (datetime.datetime.fromtimestamp(dt)) 
print (datetime.datetime.utcfromtimestamp(dt)) 
1

使用本地時區來代替 「美國/紐約」 和以下應該做的伎倆。

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>)