Python

Python Datetime Tutorial

Today we will learn how to work with dates and time. It’s an essential skill because in almost every Python program you work with time one way or another. It can be really confusing at first how to work with them because we have dates, time, timezones, timedeltas.

1. Introduction about datetime module

Module datetime is based on 3 classes:

  • date
  • time
  • datetime

For example, let’s start with class date. It receieves 3 parameters: year, month and day. Let’s try to find out what day is today:

Python

from datetime import date
today = date.today()
print(today)

It prints the day in such format: yearmonthday. For instance, we want to print it like this: day.month.year. What should we do? We can use format() method.

Python

from datetime import date
today = date.today()
print("{}.{}.{}".format(today.day, today.month, today.year))

Pretty obvious and easy, right?
Let’s take a quick look at class time. It receives parameters like hour, minute, second, microsecond. All these are not mandatory, so if we skip some, they will be initialized as zero.

Python

from datetime import datetime
datetime.now().time()

The output isn’t really pretty. What if we want to have a pretty output with the date and time alltogether but only using time module? Is it possible? For Python almost everything is possible.

Python

import time
time.ctime()

Sounds reasonable, right?
The last one is class datetime. It expands previous examples by working together with time and date. It receives all parameters from previous two, but the first 3 are a must to complete. Let’s create the variable now that stores information about date and time. Then we will print only date and only time using format() method.

Python

from datetime import datetime
now = datetime.now()
print(now)
print("{}.{}.{} {}:{}".format(now.day, now.month, now.year, now.hour, now.minute))
print(now.date())
print(now.time())

Check it out for yourself. The last thing I want to mention before we go any further. There is a method called strptime() which is used to convert string to datetime variable. There are couply things that may look like Regular Expressions you should know:

  • %d day of the month;
  • %m number of the month;
  • %y year with 2 digits;
  • %Y year with 4 digits;
  • %H hour in 24 format;
  • %M minute;
  • %S second;

2. Examples

2.1 Basic examples

Let’s start off with some basic examples. First, we want to store a data about the date and print it out. By the time you are reading this, you should already know how to do it. If you don’t know, don’t worry. We will simply create a variable that will store a data about the date we want.

Python

import datetime
day = datetime.date(2017,7,12) # be careful to NOT put 07. It will give you a syntax error
print(day) #2017-07-12

Now, if we want to print out a current day, month and year seperately, we can simply do the following:

Python

import datetime
day = datetime.date.today() 
print(day.year) #outputs the current year
print(day.month) #outputs the current month
print(day.day) #outputs the current day

Another interesting thing is we can actually know which day of the week it is by using methods weekday() and isoweekday(). Let’s try it out:

Python

import datetime
day = datetime.date.today() 
print(day.weekday()) #outputs 0
print(day.isoweekday()) #outputs 1

The only difference between those 2 methods is if today is Monday (this is my case, becase I am writing this on Monday), weekday()> returns 0 for Monday and 6 for Sunday. The isoweekday() returns 1 for Monday and 7 for Sunday. It doesn’t make much difference as you can see.
There is another cool feature called timedelta. It is basically the difference between 2 days. For example, we want to know what day will be in 15 days from today. What should we do?

Python

import datetime
now = datetime.date.today()
delta = datetime.timedelta(days=15)
print(now + delta)

Well, you might be wondering why this is important. Good thinking, let’s find out how many days are left before my birthday, for example:

Python

import datetime
now = datetime.date.today()
my_birthday = datetime.date(2017, 9 ,20) #we put 2017 as a year because we want to find out how many days are left within this year
days_left = my_birthday - now
print(days_left.days)

We have basically covered most of the datime module. However, there is one thing left. We didn’t really work with Timezones, right? I recommend you to go along with me right now and go install pytz package from pip by simply typing pip install pytz in your terminal. Then we are ready to start:

Python

import datetime
import pytz
date_timezone = datetime.datetime(2017, 7, 12, 10, 30, 45, tzinfo=pytz.UTC)
print(date_timezone)

Let’s find out how to print the current date and time including UTC using methods now() and utcnow().

Python

import datetime
import pytz
now_timezone = datetime.datetime.now(tz=pytz.UTC)
print(now_timezone)
utcnow_timezone = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
print(utcnow_timezone)

If you follow along, you may find that both outputs are the same. So it doesn’t really matter which one to use. It’s all up to you. Now let’s go and see what happens if we put specific timezone.

Python

import datetime
import pytz
utcnow_data = datetime.datetime.now(tz=pytz.UTC)
print(utcnow_data)
my_data = utcnow_data.astimezone(pytz.timezone("US/Eastern"))
print(my_data)

As you can see by its output, we see the difference between utcnow_data and my_data. So you are probably wondering, ‘How do I know which timezone to put there?’. That’s a very good question. Except Google, we can surely type in all timezones so that we won’t have to read official documentation to pytz. Note: I encourage you to read the official documentation of pytz.

Python

import datetime
import pytz
for tz in pytz.all_timezones:
   print(tz)

So you can choose any you want from that list. For example, we want to have a pretty formated date with an American version where month goes first, then we have date and finally year. What should we do? If you are thinking about the method called strftime(), then you are thinking in the right direction! What it does is to transform the data from naive to readable.

Python

import datetime
import pytz
dt_eastern = datetime.datetime.now(tz=pytz.timezone("US/Eastern"))
print(dt_eastern.strftime("%B %d %Y"))

Now, you don’t have to memorize this. If you ever feel like printing something in specific format, just go to official site and see all attributes or go to a different chapter in this article where I put all attributes, so you won’t have to google so much.
In other case, if we want to convert the string into a date, we can use a method called strptime. For instance, we have a date called July 12, 2017 and we want to convert it to a readable but structured data. Let’s do the following:

Python

import datetime
our_string = "July 12, 2017"
result = datetime.datetime.strptime(our_string, "%B %d %Y")
print(result)

2.2 Advanced examples

Let’s think about some programs that may require working with datetime module. For example, we want to understand what happened in specific date. How can we do it? Surely, we can google a lot, but Wikipedia may seem like a better answer since it has an open API. Let think what we can do:

Wikipedia.py

import datetime

answer_format = "%m/%d" # as for Month and Day
link_format = "%b_%d"
link = "https://en.wikipedia.org.wiki/{}"

while True:

   answer = input("""
      What date?
      Use the MM/DD format or QUIT""")

   if answer.upper() == "QUIT": #in case if user inputs quit

      break #the program stops

   try:

      date = datetime.datetime.strptime(answer, answer_format)
      result = link.format(date.strftime(link_format))
      print(result)

   except  ValueError:

      print("Not a valid date") #handling exception 

Well, that went well, didn’t it? Let us think about some other examples. For example, we have to work with big data or we just need to generate random data to work with it. How can we do that? Let’s say, I want to generate data for year, month, day and birthday. It doesn’t need to be specific, we just need a lot of this data.

random.py

from datetime import datetime
import random #in case we want a random data

year = random.randint(1917, 2017)
month = random.randint(1, 12)
day = random.randint(1, 28) #don't forget about February

birth_date = datetime(year, month, day)

That’s it! We can print this data and generate loop, so it iterates thus generates random data as much as we want!
Okay, this wasn’t too bad, right? Now, what if we want to know the current OS time and maybe have a timer? How can we do that?

timer.py

import datetime
import sys

if __name__ == "__main__":

   while True:
      do = input("Enter:\n\"T\" to use the timer, \"C\" to check the current time and \"Q\" to exit: ")
      if do.upper() == "T":

         while True:

            start = input("Enter any KEY to start:")
            if start:
               break

         startTime = datetime.datetime.now()
         print("You Started at ", startTime.hour, ":", startTime.minute, ":", startTime.second, sep = "")

         while True:

            end = input("Enter any KEY to stop:")
            if end:
               break

         endTime = datetime.datetime.now()
         print("You ended at ", endTime.hour, ":", endTime.minute, ":", endTime.second, sep = "")
         print("You took", endTime.hour - startTime.hour, "Hour(s),", endTime.minute - startTime.minute, "Minute(s),", endTime.second - startTime.second, "Second(s)")

      elif do.upper() == "Q":
         sys.exit()

      elif do.upper() == "C":
         hms = datetime.datetime.now()

         if hms:
               break
         hms = datetime.datetime.now()
         print(hms.hour, ":", hms.minute, ";", hms.second, sep = "")

      else:
         print("That is not a valid command")

3. Useful tips and cool tricks

There are many cool things you can do with datetime module. Let’s cover some of them. How can we access the current month name with a full month name? Well, that’s pretty easy…

Python

import datetime
print(datetime.date.today().strftime("%B"))

Well, this one was easy. What if we want to have a current date in day name and month name? Sounds like something similar? Well, it is!

Python

import datetime
print(datetime.date.today().strftime("%A, %d %B, %Y"))

Now, let’s think we want to have a program that works and runs just fine but with some pause in between? What should we do? Well, that is quite easy actually, all thanks to time module.

Python

import time
for i in range(10):
   time.sleep(5)
   print("Slept for 5 seconds")

Basically we are getting the program that prints 10 times with an interval of 5 seconds the string "Slept for 5 seconds". It’s pretty easy. Now, what we need here is some info showing what strftime() and strptime() do:

  • %a weekday as locale’s abbreviated name
  • %A weekday as locale’s full name
  • %w weekday as a decimal number, where 0 is Sunday and 6 is Saturday
  • %d day of the month as a zero-padded decimal number>
  • %b month as locale’s abbreviated name
  • %B month as locale’s full name
  • %m month as a zero-padded decimal number
  • %y year without century as a zero-padded decimal number
  • %Y year without century as a decimal number
  • %H hour(24) as a zero-padded decimal number
  • %I hour(12) as a zero-padded decimal number
  • %p equivalent of either AM or PM
  • %M minute as a zero-padded number
  • %S second as a zero-padded number
  • %z UTC offset in the form ++HHMM or -HHMM
  • %Z time zone name
  • %j day of the year as a zero-padded decimal number
  • %U week number of the year
  • %c locale’s appropriate date and time presentation
  • %X another date and time representation

4. Summary

We have learnt how to do simple things with datetime module. Let’s understand basic principle of the entire module, shall we?

Python shell

import datetime
help(datetime)

We will see a lot of methods but those that we need are: date, time, and datetime. Each of them has a special structure:

  1. date(year, month, day) – all parameters are essential and can’t be missing
  2. time([hour], [min], [sec], [microsec]) – if any are missing, they are initialized as 0
  3. datetime(year, month, day, [hour], [min], [sec], [microsec]) – only first 3 parametes are mandatory

5. Homework

There will be only one homework but with different levels of complexity. You are free to choose any level.
The task is to create a program that will tell you how many days are left before the “day” (special day like birthday or whatever)
Easy level: in the program, you already have programmed “day”, so there is no user interaction. The program works any day and returns different data.
Medium level: the program asks the user about the “day” (name, date, etc.). It returns different data depending on the day.
Hard Level: it has a solid GUI interface that has an input field for a user to put the data about the “day”. It returns different data depending on the day. P.S. you can use Tkinter or Pygame to do that.
Guido level: it has a solid GUI interface, and everytime you check how many days/hours are left before the “day”, it puts the data about your actions in the program in a special file (for example, in .csv file). Moreover, it has a neural network that analyzes how many times and when you opened the app, so within some time it automatically opens it for you or/and have some notifications to open the program.

6. Download the Source Code

You can find 3 python programs that we discussed in advanced examples here.

Download
You can download the full source code of this example here : datetime.zip

Aleksandr Krasnov

Aleksandr is passionate about teaching programming. His main interests are Neural Networks, Python and Web development. Hobbies are game development and translating. For the past year, he has been involved in different international projects as SEO and IT architect.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button