Pandas Supplemental Notebook: Dates and times
Contents
Pandas Supplemental Notebook: Dates and times¶
In this notebook, we’ll work with dates and times in Python.¶
Full documentation: https://docs.python.org/3/library/datetime.html¶
Resources used in the making of this notebook:¶
https://www.programiz.com/python-programming/datetime¶
import datetime
The datetime module includes the following classes:¶
datetime, timedelta, date, time, tzinfo, timezone¶
Get the current time by making a call to datetime’s datetime.now method. It produces a datetime object with the year, month, day, hour, minute, second and microsecond.¶
x = datetime.datetime.now()
x
datetime.datetime(2023, 1, 19, 17, 26, 16, 499364)
print(x)
2023-01-19 17:26:16.499364
This datetime object contains a variety of attributes that we can list, as well as reformat.¶
x.year
2023
x.month
1
We can use the strftime method on a datetime object in order to produce date/time strings in a specified format.¶
We’ll play around with a few of these options in the cells below, but visit https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior for full documentation of strftime!¶
# %A will list the full name of the day of the week:
x.strftime("%A")
'Thursday'
# %y will list the two-digit year, %m, the two-digit month, and %d, the two-digit date:
print(x.strftime("%y"))
print(x.strftime("%m"))
print(x.strftime("%d"))
23
01
19
# We can also define a new object called "today" as the output from our strftime method, still using datetime.now(),
# which we called at the beginning of this notebook, and defined as "x".
today = x.strftime("%y%m%d")
print(today)
230119
# Let's add the hour to that!
x.strftime("%y%m%d%H")
'23011917'
# What if we wanted to define a more human-friendly string to use in a title of a graphic?
x.strftime("%y%m%d at %HZ")
'230119 at 17Z'
Exercise: Using the documentation in the link above, create a title string from today’s date in the format: “DD Month YYYY at HHMM UTC”. For example: 10 June 1983 at 1435 UTC ¶
# Write your code here; solution can be loaded from next cell
# %load /spare11/atm533/common/week4/04s.py
'''
04s.py
'''
# x was already set to today's date up above
x.strftime("%d %B %Y at %H%M UTC")
'19 January 2023 at 1726 UTC'
We can create datetime objects with the datetime.datetime() class constructor.¶
y = datetime.datetime(2019,6,20,9,15,0)
y
datetime.datetime(2019, 6, 20, 9, 15)
y.year
2019
y.month
6
y.hour
9
y.minute
15
Besides the datetime class, there is also just a plain date class, that only deals with dates (not times). A “time” class also exists with a similar purpose.¶
from datetime import date, time
a = date(2020,3,12)
print(a)
2020-03-12
today = date.today()
print("Current date = ", today)
Current date = 2023-01-19
print ("Current year is: ", today.year)
print ("Current month is: ", today.month)
print ("Current day is: ", today.day)
Current year is: 2023
Current month is: 1
Current day is: 19
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b)
# time(hour, minute and second)
c = time(hour = 11, minute = 34, second = 56)
print("c =", c)
# time(hour, minute, second, microsecond)
d = time(11, 34, 56, 234566)
print("d =", d)
a = 00:00:00
b = 11:34:56
c = 11:34:56
d = 11:34:56.234566
These look like strings. Are they?¶
type(b)
datetime.time
No … they are datetime objects of class time.¶
print("hour =", d.hour)
print("minute =", d.minute)
print("second =", d.second)
print("microsecond =", d.microsecond)
hour = 11
minute = 34
second = 56
microsecond = 234566
It is “cleaner” to import the various classes available to us in the datetime library by importing them in the following way (we will discuss timedelta shortly!):¶
from datetime import datetime, timedelta
#datetime(year, month, day)
a = datetime(2018, 11, 28)
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)
2018-11-28 00:00:00
2017-11-28 23:55:59.342380
a = datetime(2019, 3, 23, 1, 10, 30)
print("year =", a.year)
print("month =", a.month)
print("hour =", a.hour)
print("minute =", a.minute)
year = 2019
month = 3
hour = 1
minute = 10
We can also use some basic arithmetic to calculate time between dates!¶
t1 = date(year = 2020, month = 7, day = 12)
t2 = date(year = 2019, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, second = 33)
t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, second = 13)
t6 = t4 - t5
print("t6 =", t6)
print("type of t3 =", type(t3))
print("type of t6 =", type(t6))
t3 = 202 days, 0:00:00
t6 = -333 days, 1:14:20
type of t3 = <class 'datetime.timedelta'>
type of t6 = <class 'datetime.timedelta'>
Datetime’s timedelta class allows us to easily compute dates and times earlier or later than a base time.¶
Note that these objects are defined as a period of time, rather than a date.¶
t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
t3 = 14 days, 13:55:39
Note that “months” is not a valid timedelta argument!! Can you think why that is the case?¶
# This cell won't work
#t1 = timedelta (months = 1)
t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
print("t3 =", abs(t3))
t3 = -1 day, 23:59:39
t3 = 0:00:21
t = timedelta(days = 6, hours = 13, seconds = 53, microseconds = 232436)
print("total seconds =", t.total_seconds())
print("total minutes =", t.total_seconds()/60)
total seconds = 565253.232436
total minutes = 9420.887207266667
As we learned at the beginning of this notebook, datetime’s datetime class includes the strftime method which takes a datetime object and converts it into a string, which can be formatted.¶
# current date and time
now = datetime.now()
t = now.strftime("%H:%M:%S")
print("time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
time: 17:26:16
s1: 01/19/2023, 17:26:16
s2: 19/01/2023, 17:26:16
Conversely, the strptime method takes an appropriately-formatted date/time string and converts it into a datetime object.¶
date_string = "16 January, 2020"
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
date_string = 16 January, 2020
date_object = 2020-01-16 00:00:00
Calculate a new date and convert it into its string representation¶
new_date_object = date_object + timedelta (days=14)
print(new_date_object)
new_date_string = new_date_object.strftime ("%d %B, %Y")
print(new_date_string)
2020-01-30 00:00:00
30 January, 2020
Timezone can be manipulated via the pytz library. pytz stands for Python Time Zone.¶
import pytz
# Uncomment to get a list of all possible timezones
#for tz in pytz.all_timezones:
# print (tz)
# What time is our computer set to?
system = datetime.now()
print("The current time on this computer is:", system.strftime("%m/%d/%Y, %H:%M:%S %Z"),"\n")
print("Here is the current time in some other timezones:\n")
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S %Z"))
tz_Pacific = pytz.timezone('US/Pacific')
datetime_Pacific = datetime.now(tz_Pacific)
print("Pacific:", datetime_Pacific.strftime("%m/%d/%Y, %H:%M:%S %Z"))
tz_Amsterdam = pytz.timezone('Europe/Amsterdam')
datetime_Amsterdam = datetime.now(tz_Amsterdam)
print("Amsterdam:", datetime_Amsterdam.strftime("%m/%d/%Y, %H:%M:%S %Z"))
tz_Newfoundland = pytz.timezone('Canada/Newfoundland')
datetime_Newfoundland = datetime.now(tz_Newfoundland)
print("Newfoundland:", datetime_Newfoundland.strftime("%m/%d/%Y, %H:%M:%S %Z"))
The current time on this computer is: 01/19/2023, 17:26:16
Here is the current time in some other timezones:
NY: 01/19/2023, 12:26:17 EST
Pacific: 01/19/2023, 09:26:17 PST
Amsterdam: 01/19/2023, 18:26:17 CET
Newfoundland: 01/19/2023, 13:56:17 NST