ISO time (ISO 8601) in Python


Question

I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone (ET).

How do I take the file's ctime and convert it to an ISO time string that indicates the Eastern Time Zone (and takes into account daylight savings time, if necessary)?

1
241
10/24/2018 3:10:18 AM

Local to ISO 8601:

import datetime
datetime.datetime.now().isoformat()

UTC to ISO 8601:

import datetime
datetime.datetime.utcnow().isoformat()

Local to ISO 8601 without microsecond:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()

UTC to ISO 8601 with TimeZone information (Python 3):

import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()

Local to ISO 8601 with TimeZone information (Python 3):

import datetime, time

# Calculate the offset taking into account daylight saving time
utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(tzinfo=datetime.timezone(offset=utc_offset)).isoformat()

For Python 2, see and use pytz.

367
10/24/2018 2:50:30 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon