Does datetime.fromtimestamp(os.path.getctime()) in Python give me a timezone-aware value?

陌路散爱 提交于 2020-01-03 19:03:25

问题


I am using calls such as this in Python 3.4:

x = datetime.fromtimestamp(os.path.getctime(somefilename))
y = datetime.fromtimestamp(os.path.getmtime(somefilename))

Will x and y be timezone-aware, as per the definition of that term in the datetime documentation? Does this vary between platforms? I assume that in theory the ctime and mtime of a file are measured against the seconds since the epoch in UTC, so the answer should be yes?

If so, is that true across all/most POSIX platforms? Specifically, is it true on modern Linux/OS X?

If not, is there a better way to handle this? How can I get timezone-aware ctime and mtime data? What timezone do platforms use for expressing/storing ctime and mtime?


回答1:


On OSX, at least, os.path.getctime returns a TZ-naive datetime in the system's timezone.

$ date
Mon Jun  8 15:08:40 PDT 2015

$ touch new_file
$ python  
>>> from datetime import datetime
>>> import os
>>> datetime.fromtimestamp(os.path.getctime('new_file'))
datetime.datetime(2015, 6, 8, 15, 8, 42)
>>> print datetime.fromtimestamp(os.path.getctime('new_file')).tzinfo
None

time.timezone will give you the local timezone offset in seconds, not accounting for DST. The pytz library will probably be very useful to you.




回答2:


os.path.getctime() returns a float that represents "seconds since epoch" (values returned by time.time()) -- it is not a datetime object naive or otherwise.

datetime.fromtimestamp() returns a naive datetime object representing local time unless you pass the explicit tzinfo object as a second parameter, code example.



来源:https://stackoverflow.com/questions/30719734/does-datetime-fromtimestampos-path-getctime-in-python-give-me-a-timezone-awa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!