Python datetime and pytz module

By | August 5, 2019

Here in this tutorial we will discuss python datetime module and also learn how to deal with date and time in python.

Python datetime module

Python has an inbuilt module datetime which deal with the date and time. With the help of this module, we can use the time and date in our program.

There are many methods associated with the datetime module let’s have a look at some of the most important.

datetime module to get the current date and time:

import datetime
current_date_nd_time = datetime.datetime.now()
print(current_date_nd_time)

Output:

2019-08-02 20:34:54.969255

Behind the code:

We use the datetime.now() method of datetime to get the current date and time. The datetime.now() method return a datetime object in the form of current date and time.

In the above output, 2019-08-02 is the date in the form of yyyy-mm-dd and 20:34:54.969255 in the form of hh-mm-ss.ss

datetime module to get only current date:

Example:

import datetime
today_date = datetime.date.today()
print('its:',today_date)

output:

its: 2019-08-02

Behind the code:

The datetime.date.today() method return local date in the form of yyyy-mm-dd

Datetime all inbuilt classes

datetime is a module which mean it contains may .py files, that means it must have many inbuilt classes, let’s see all the classes which have been defined in the datetime module.

we will use the dir() method to print out all the classes defined in the datetime module:

Example:

import datetime
print(dir(datetime))

Output:

['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']

The most common classes of datetime modules are:

  • date
  • datetime
  • time
  • timezone
  • timedelta 

datetime module date class (datetime.date)

As we know that datetime module has many inbuilt classes, date is one of them. With the help of this date class we can perform many tasks.

Let’s see some example of datetime date class.

1: Use datetime.date to create a datetime object:

With the help of datetime.date we can create a datetime object and define a date.

Example:

from datetime import date
sam_DOB = date(1999,11,26)

print("Sam date of birth is:", sam_DOB)
print('the data type if sam_DOB variable is',type(sam_DOB))

Output:

Sam date of birth is: 1999-11-26
the data type if sam_DOB variable is <class 'datetime.date'>

Behind the code:

We import the date class from the datetime module and with the help of date() we create a date object. The date() class accept 3 arguments year, month and day to create a date object.

2: date class methods

In one of the above examples we have used the date.today() method to print the current date.

What if we want only the particular year, month, and day from the day.today() object, for this we can use that datetime object to access special attribute from the date class which are obj.year, obj.month and obj.day.

Example:

from datetime import date
today_date = date.today()    #datetime.date object by python for current date
sam_DOB = date(1999,11,26)   #datetime.date object created by user specified date

print("Sam date of birth year is:", sam_DOB.year)
print("We are in:", today_date.year)

print("sam date of birth month is:", sam_DOB.month)
print("Today is:", today_date.day)

Output:

Sam date of birth year is: 1999
We are in: 2019
sam date of birth month is: 11
Today is: 2

Datetime time Class (datetime.time):

Datetime module contains time class which deal with time in Hour, minutes, seconds and microseconds. One of the above examples when we printed out the today’s complete date with current time the time was formatted in hour:minutes:seconds.microsecond

1. Lets use the .time() to create datetime.time object

from datetime import time
dinner_time = time(21,30,00)
print("My dinner time is",dinner_time)

Output:

My dinner time is 21:30:00

Behind the code:

Here dinner_time is a time object.

2. Get hour, minutes, seconds and Microsecond from a time object.

With the help of hour, minute, second and microsecond we can grab the specific hours and minutes from the time object:

Example:

from datetime import time
dinner_time = time(21,30,50,98937)
print('dinner Hour is:' ,dinner_time.hour)
print('dinner minute is:',dinner_time.minute)
print('second is:', dinner_time.second)
print('micro second is:',dinner_time.microsecond)

Output:

dinner Hour is: 21
dinner minute is: 30
second is: 50
micro second is: 98937

datetime datetime class (datetime.datetime) (from datetime import datetime)

The datetime module has a class with similar name datetime, the datetime class is used to deal with both date and time, let’s see some example.

Example:

from datetime import datetime
# datetime(year, month, day, hour, minute, second, microsecond)
datetime_obj = datetime(2019,1,1,10,20,40,12323)

print('year:',datetime_obj.year)
print('month',datetime_obj.month)
print('day',datetime_obj.day)
print('hour',datetime_obj.hour)
print('minute',datetime_obj.minute)

Output:

year: 2019
month 1
day 1
hour 10
minute 20

datetime timedelta class(datetime.timedelta) or (from datetime import timedelta):               

timedelta is one of the important and logical concepts of datetime module, the timedelta is used to find out the difference between two time period.

Let’s see some examples:

Example:

from datetime import timedelta
# timedelta(weeks, days, hours, minutes, seconds, microseconds)
time_1 = timedelta(weeks=10)
time_2 = timedelta(weeks=2,hours=10,minutes=40)
time_3 = time_1 - time_2
print("the time difference between time_1 and time_2 is:",time_3)

Output:

the time difference between time_1 and time_2 is: 55 days, 13:20:00

Python Date formatting:

By default python datetime module and all its class accept date and time in yyyy-mm-dd hh:mm:ss.ms for and print the date and time in same format.

But in datetime module, we have a special method strftime() which can format the date object according to the user will

We can format the date time in many formants such as dd/mm/yyyy or yyyy/dd/mm

Example:

from datetime import datetime
current_date = datetime.now()
#datetime_object.strftime("%d/%m/%Y, %H:%M:%S")
change_format_current_date = current_date.strftime("%d/%m/%Y, %H-%M")
print('default format is: ',current_date)
print('changed format is: ',change_format_current_date)

Output:

default format is:  2019-08-02 23:21:41.907656
changed format is:  02/08/2019, 23-21

pytz python timezone module

python has a very interesting module pytz which stand for python time zone with the help of this module we can easily printed the date, time of different time zones or countries.

This is a third-party library you might have to download this first,

use pip install pytz in your command terminal

let’s see an example:

Example:

from datetime import datetime
import pytz

my_time = datetime.now()
new_york_time = datetime.now(pytz.timezone('America/New_York'))
print("My country:", my_time.strftime("date %d/%m/%Y time %H:%M"))
print('New York:', new_york_time.strftime("date %d/%m/%Y time %H:%M"))

Output:

My country: date 02/08/2019 time 23:38
New York: date 02/08/2019 time 14:08

Python Tutorials


Introduction

Flow Control

Functions

Datatypes

File Handling

Object & Class

Additional Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *