Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the file modification date in UTC from Python

Tags:

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

like image 688
user1457432 Avatar asked Jul 10 '12 00:07

user1457432


People also ask

How do I get the date modified of a file in Python?

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.

How do I get the current UTC timestamp in python?

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.

Which of the following function will be used to get the last modification time of a file in Python?

getmtime() method in Python is used to get the time of last modification of the specified path.


2 Answers

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)) 
like image 145
mgilson Avatar answered Sep 29 '22 22:09

mgilson


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>) 
like image 44
ely Avatar answered Sep 29 '22 20:09

ely