datetimes Flashcards
1
Q
Manually create one datetime object and also just its date (no hours/mins/secs)
A
given_dt = dt.datetime(2022, 9, 30)
given_date = given_dt.date()
Note: these are two different object types!
2
Q
Calculate unix time from datetime
A
(given_dt - dt.datetime(1970, 1, 1)).total_seconds()
3
Q
Create datetime object from date string
A
from dateutil.parser import parse
parse(date_string) # easy but slow
strptime(date_string, %Y-%M-%d) # or whatever
4
Q
Turn pandas date strings col into datetimes and also just dates (no hours/mins/secs)
A
pd.to_datetime(df.str_date_col).date()
5
Q
Create date string from datetime object
A
strftime(date_string, %Y-%M-%d) # or whatever