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
Using time module to get file creation & modification date or time in Python. We will use getctime() and getmtime() function, found inside the path module in the os library, for getting the creation and modification times of the file.
Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
getmtime() method in Python is used to get the time of last modification of the specified path.
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))
Use your local timezone in place of "America/New_York" and the following should do the trick.
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With