Python is able to work with time quite efficiently, as long as the coder is aware of a few functions.
In the `datetime.datetime` package:
– `strptime` is used to parse a text string representing a datetime object into a datetime object.
– `strftime` is used to turn a datetime object into a string representing a datetime object.
– `timedelta` can be used to add to or delete a certain amount of time from a datetime object.
You will need basic Python programming and datetime skills for this lab:
– [Certified Associate in Python Programming Certification](https://linuxacademy.com/cp/modules/view/id/470)
– [Python’s datetime](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes)
Successfully complete this lab by achieving the following learning objectives:
- Convert All Due Date Strings to datetime Objects
Using the SQLite applications you have already developed, you pull all the datetimes and book titles from the database. SQLite has no datetime date type, and so we are storing them as strings. These strings need to be turned into actual datetime objects.
Update the code so that the datetime string is converted to a datetime object, and add the last minute of the day to it:
from datetime import datetime, timedelta # due date data from db title_due_dates = [ ["Oh Python! My Python!", "2020-11-15"], ["Fun with Django", "2020-06-23"], ["When Bees Attack! The Horror!", "2020-12-10"], ["Martin Buber's Philosophies", "2020-07-12"], ["The Sun Also Orbits", "2020-10-31"] ] # replace the string date with a date object for each title # add the last minute of day to each due date # add a timedelta representing the last minute of the day for book in title_due_dates: due_date = datetime.strptime(book, "%Y-%m-%d") due_date = due_date + timedelta(hours=23, minutes=59) book = due_date
Congratulations! You have shown that you can convert strings to datetime objects.
- Turn All Resulting datetime Objects Into a String
Before we can use our SQLite applications to upload the new due dates, we need to convert them to string representation.
python add_time.py. This will result in an
add_time.pyso that the datetime object is converted back to a string:
# previous code omitted # replace the datetime object with a string representation # remember SQLite stores dates as strings for book in title_due_dates: book = book.strftime("%Y-%m-%d %H:%M:%S")
Congratulations! You have shown that you can convert datetime objects to strings.