4

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?

Andrew Ferrier
  • 16,664
  • 13
  • 47
  • 76

2 Answers2

2

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.

Erin Call
  • 1,764
  • 11
  • 15
  • Check the file's `tzinfo` attribute isn't very useful as the `fromtimestamp` function allows you to pass in the timezone as a `tzinfo` instance. Without it, it just uses the local timezone. I'm guessing throughout the `datetime` module `None` must represent "just use the local timezone". – Xevion Nov 03 '20 at 23:54
1

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670