Skip to content

Instantly share code, notes, and snippets.

@crabba
Last active February 22, 2020 23:03
Show Gist options
  • Save crabba/1c3d15a2747125c7335fcd975c6e0d4d to your computer and use it in GitHub Desktop.
Save crabba/1c3d15a2747125c7335fcd975c6e0d4d to your computer and use it in GitHub Desktop.
Python Datetimes
from datetime import datetime, timezone, timedelta
# Using Boto 3 EC2
launch_time = ec2.launch_time
print("launch_time {} tz {}".format(launch_time, launch_time.tzinfo))
now = datetime.now()
print("now {} tz {}".format(now, now.tzinfo))
try:
diff = now - launch_time
except TypeError as err:
print("Error: {}".format(err))
unow = datetime.now(timezone.utc)
print("unow {} tz {}".format(unow, unow.tzinfo))
diff = unow - launch_time
print("diff {}".format(diff))
print("diff {}".format(timedelta(days = diff.days, seconds = diff.seconds)))
# launch_time 2020-02-21 21:19:21+00:00 tz tzutc()
# now 2020-02-22 17:49:46.575370 tz None
# Error: can't subtract offset-naive and offset-aware datetimes
# unow 2020-02-22 22:49:46.575448+00:00 tz UTC
# diff 1 day, 1:30:25.575448
# diff 1 day, 1:30:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment