Last active
July 1, 2023 21:40
-
-
Save choww/77733680606998add2f0c8560ebf1593 to your computer and use it in GitHub Desktop.
Working with Dates in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime, date, timedelta, timezone, timestamp | |
# create today's date that's offset-aware--datetime.today() seems to do the same thing | |
now = datetime.now(timezone.utc) | |
# convert datetime object to formatted string | |
today = now.strftime('%Y/%m/%d') | |
# calling `.astimezone()` without a timezone object defaults to the local timezone | |
pdt = now.astimezone() | |
# turn date string into timestamp | |
date = datetime.strptime('2023-06-30', '%Y-%m-%d') | |
# timestamp unit = seconds | |
timestamp = datetime.timestamp(date) | |
# turn date string into datetime object | |
# format code list: https://www.programiz.com/python-programming/datetime/strptime | |
date = datetime.strptime('2022/08/22', '%Y/%m/%d') | |
# make the datetime object offset-aware | |
date.replace(tzinfo=timezone.utc) | |
# create a custom date | |
date = datetime(2022, 9, 21, 0,0,0, tzinfo=timezone.utc) | |
# create the earliest datetime object that's offset-aware | |
min = datetime.min.replace(tzinfo=timezone.utc) | |
# calculate x days ago from today | |
date.today() - timedelta(days=400) | |
datetime.today() - timedelta(days=7) | |
# get the difference in days, seconds, or ms between two dates | |
date1 = datetime.today() | |
date2 = datetime.today() - timedelta(days=40) | |
# this will return a timedelta object, call diff.days, diff.seconds, or diff.microseconds to get the diff in those units | |
diff = date1 - date2 | |
# convert datetime.date to timestamp | |
dt = datetime.combine(date.today(), datetime.min.time()) | |
timestamp = datetime.timestamp(dt) | |
# convert datetime.datetime to timestamp | |
date = datetime.today() | |
timestamp = datetime.timestamp(date) | |
# convert timestamp to date | |
date = datetime.fromtimestamp(1557263690122) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment