python

How to get the file modification date in UTC from Python


I want to get the modification date of a file in UTC from Python. The following code returns dates in my Linux configured time zone (GMT-5). I want it in UTC. Or how do I get the os configured time zone to convert it with 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)

Thanks


Solution

  • Try datetime.datetime.utcfromtimestamp

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