If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.
datetime is a module for handling date and time. If you need a quick refresher, read here about importing modules.
First, you need to import
>>> from datetime import datetime >>> print(datetime.now()) 2019-12-18 13:33:11.223728
strftime refers to string representations of time with formatting.
Formatting datetime output is done with many different codes. Here are a few common ones.
|Format Code||What it Does||Output|
||Day of Month||01, 02, …, 31|
||Hours (24-hour clock)||00, 01, …, 23|
||Hours (12-hour clock)||01, 02, …, 12|
||Minutes||00, 01, …, 59|
||Seconds||00, 01, …, 59|
If you've been in the military, it's likely you used 24-hour time to avoid confusion. For example 1300 hrs would be the same as 1 pm.
Here's an example using 24-hr time.
>>> from datetime import datetime >>> now = datetime.now() >>> time = now.strftime("%H%M") >>> print(time) 1353
>>> from datetime import datetime >>> another_time = now.strftime("Today is %A, %d %B %Y.") >>> print(another_time) Today is Wednesday, 18 December 2019.
strptime takes strings and creates objects from them.
strptime() as being backwards from
strftime(). Consider this example to be an intro to parsing data.
>>> from datetime import datetime >>> a_date = "Today is Wednesday, 18 December 2019." >>> date_object = datetime.strptime(a_date, "Today is %A, %d %B %Y.") >>> print(date_object) 2019-12-18 00:00:00
>>> from datetime import date >>> print(date.today()) # return current local date 2019-12-18
from datetime import time >>> print(time(12,3)) # prints exactly what you give it, in time format 12:03:00
>>> from datetime import date >>> now = datetime(year = 2019, month = 12, day = 18, hour = 12, minute = 13, second = 0) >>> new_year = datetime(year = 2020, month = 1, day = 1, hour = 0, minute = 0, second = 0) >>> remaining = new_year - now >>> print(remaining) 13 days, 11:47:00
The below example shows the difference between to
>>> from datetime import date >>> today = date(year=2019, month=12, day=18) >>> new_year = date(year=2020, month=1, day=1) >>> time_left_in_year = new_year - today >>> print(time_left_in_year) 14 days
For more info on the
datetime module, check out the Python docs.
Series loosely based on