Datetime notebook, ATM350 Spring 2024
Contents
Datetime notebook, ATM350 Spring 2024 ¶
Imports¶
import datetime
The datetime
module includes the following classes:¶
date
datetime
time
timedelta
timezone
tzinfo
datetime, timedelta, date, time, tzinfo, timezone
It also includes these associated methods:¶
strftime
strptime
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(2024, 4, 30, 1, 55, 58, 517371)
print(x)
2024-04-30 01:55:58.517371
This datetime object contains a variety of attributes that we can list, as well as reformat.¶
x.year
2024
x.month
4
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 or %a will list the full name of the day of the week:
x.strftime("%A")
'Tuesday'
# %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"))
24
04
30
Let’s combine the year, month, and day, into a date string we’re used to using in ATM 350! We can define a new object called today as the output from our strftime method, still using our the datetime object “x” we created using the datetime.now() method:¶
today = x.strftime("%y is the year, %m is the month, and %d is the day")
print(today)
24 is the year, 04 is the month, and 30 is the day
# Let's add the hour to that!
x.strftime("%y%m%d%H")
'24043001'
# 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")
'240430 at 01Z'
Exercise: Using the documentation in the link below, 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 :¶
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
# Enter your code here:
# %load /spare11/atm350/common/feb29/datetime_1.py
We can also create datetime objects with the datetime.datetime() class constructor.¶
y = datetime.datetime(2024,5,14,17,29,0)
y
datetime.datetime(2024, 5, 14, 17, 29)
print(y.year)
print(y.month)
print(y.hour)
print(y.minute)
2024
5
17
29
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(2024,11,2)
print(a)
2024-11-02
Just as there was a now() method for the datetime
class, there is a today() method for the date
class.¶
today = date.today()
print("Current date = ", today)
Current date = 2024-04-30
print ("Current year is: ", today.year)
print ("Current month is: ", today.month)
print ("Current day is: ", today.day)
Current year is: 2024
Current month is: 4
Current day is: 30
Here are some examples of the time
class of datetime objects:¶
# time(hour = 0, minute = 0, second = 0) ... In other words, no arguments provided, so defaults of 0 are used for hour, minute, and second:
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(7, 29, 18)
print("b =", b)
# time(hour, minute and second)
c = time(hour = 7, minute = 29, second = 18)
print("c =", c)
# time(hour, minute, second, microsecond)
d = time(7, 29, 18, 679122)
print("d =", d)
a = 00:00:00
b = 07:29:18
c = 07:29:18
d = 07:29:18.679122
These look like strings. Are they?¶
type(b)
datetime.time
No … they are datetime objects of class time.¶
We can also call specific attributes of these objects:¶
print("hour =", d.hour)
print("minute =", d.minute)
print("second =", d.second)
print("microsecond =", d.microsecond)
hour = 7
minute = 29
second = 18
microsecond = 679122
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!). Note that this allows us to just call the class “datetime” as opposed to datetime.datetime.¶
from datetime import datetime, timedelta
#A few examples of creating datetime objects:
#datetime(year, month, day)
a = datetime(2024, 11, 28)
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2006, 4, 23, 23, 55, 59, 342380)
print(b)
2024-11-28 00:00:00
2006-04-23 23:55:59.342380
We can also use some basic arithmetic to calculate time between dates!¶
t1 = date(year = 2024, month = 7, day = 12)
t2 = date(year = 2023, 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 = 23 days, 12:05:27
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
Timedelta includes a total_seconds() method:¶
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
Note that “months” is not a valid timedelta argument!! Why not?¶
t1 = timedelta (months = 1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 1
----> 1 t1 = timedelta (months = 1)
TypeError: 'months' is an invalid keyword argument for __new__()
However, if our datetime
object includes a month, we can compute a time delta in months via the relativedelta
function from a separate package, dateutil
:¶
from dateutil.relativedelta import relativedelta
today + relativedelta(months=2)
datetime.date(2024, 6, 30)
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. Review from earlier…¶
# current date and time
curtime = datetime.now()
string1 = curtime.strftime("%H:%M:%S")
print("string1:", string1)
string2 = curtime.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("string2:", string2)
string3 = curtime.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("string3:", string3)
string1: 01:56:06
string2: 04/30/2024, 01:56:06
string3: 30/04/2024, 01:56:06
Conversely, the strptime method takes an appropriately-formatted date/time string and converts it into a datetime object.¶
#Start with a string:
date_string = "10 June, 2023"
print("date_string =", date_string)
#Convert to a date object, making sure to include the appropriate formatting we used in the string:
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
date_string = 10 June, 2023
date_object = 2023-06-10 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)
2023-06-24 00:00:00
24 June, 2023
Exercise: Create a date object from a string “1900 UTC 22 May 2014” ¶
#Enter your code here:
# %load /spare11/atm350/common/feb29/datetime_2.py
Timezone can be manipulated via the pytz library. pytz stands for Python Time Zone.¶
import pytz
# What time is our computer set to?
system = datetime.now()
print("system:", system.strftime("%m/%d/%Y, %H:%M:%S"))
system: 04/30/2024, 01:56:08
Here we can pass a specific time zone into the datetime.now() method:¶
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY:", datetime_NY.strftime("%m/%d/%Y, %H:%M:%S"))
NY: 04/29/2024, 21:56:27
tz_Amsterdam = pytz.timezone('Europe/Amsterdam')
datetime_Amsterdam = datetime.now(tz_Amsterdam)
print("Amsterdam:", datetime_Amsterdam.strftime("%m/%d/%Y, %H:%M:%S"))
Amsterdam: 04/30/2024, 03:56:27