Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Path().stat().st_time timezone?

I am trying to get a file's last modified time using Python 3.8 in Cygwin.

So if I do stat .profile I get:

  File: .profile
  Size: 1236            Blocks: 4          IO Block: 65536  regular file
Device: 46e61a95h/1189485205d   Inode: 8162774324632653  Links: 1
Access: (0755/-rwxr-xr-x)  Uid: (197609/   pepol)   Gid: (197609/   pepol)
Access: 2020-09-14 15:16:04.773101900 +0700
Modify: 2020-09-14 15:15:21.977809000 +0700
Change: 2020-09-14 15:16:04.055602500 +0700
 Birth: 2020-09-14 15:16:04.052652900 +0700

But if I try getting the file's timestamp using Python:

from pathlib import Path
from datetime import datetime

p1 = Path(".profile")
p1st = p1.stat()
dts = datetime.fromtimestamp(p1st.st_mtime)
print(str(dts))

I got this 'naive' (timezoneless) instead:

2020-09-14 09:15:21.977809

Now here's where I get confused:

  • As shown in the stat output, my timezone is UTC+07:00
  • My country does NOT have DST
  • Windows' timezone is properly set
  • 15:15:21.977809000 +0700 is equivalent to 08:15:21.977809000 +0000

Why is the timestamp as fetched by pathlib.Path().stat() is 1 hour ahead of what the UTC timestamp should be? What timezone is it actually using?

like image 934
pepoluan Avatar asked Oct 24 '25 16:10

pepoluan


1 Answers

Make sure that in cygwin, you use Cygwin's Python. You can check which Python version cygwin uses with $which python3. That should return e.g. /usr/bin/python3.

  • if you use a Windows Python installation from within Cygwin, it won't be able to determine the machines' time zone (OS setting) correctly (the Windows Python is configured to do that on Windows, not in a Unix environment and vice versa).

Side note, since the timestamps returned by pathlib.Path().stat() are POSIX timestamps, so you could use e.g. datetime.fromtimestamp(p1st.st_mtime, tz=timezone.utc) to get UTC straight away.

like image 101
FObersteiner Avatar answered Oct 26 '25 05:10

FObersteiner