Python Working With Dates & Times

 

Working With Dates & Times

Datetime

Python has a built-in datetime module which provides convenient objects to work with dates and times.

Code

import datetime
PYTHON

Datetime classes

Commonly used classes in the datetime module are:

  • date class
  • time class
  • datetime class
  • timedelta class

Working with 'date' class

Representing Date

A date object can be used to represent any valid date (year, month and day).

Code

import datetime
date_object = datetime.date(2019, 4, 13)
print(date_object)
PYTHON

Output

2019-04-13

Date Object

Code

from datetime import date
date_obj = date(2022, 2, 31)
print(date_obj)
PYTHON

Output

ValueError: day is out of range for month

Today’s Date

Class method

today()
returns a date object with today’s date.

Code

import datetime
date_object = datetime.date.today()
print(date_object)
PYTHON

Output

2021-02-05

Attributes of Date Object

Code

from datetime import date
date_object = date(2019, 4, 13)
print(date_object.year)
print(date_object.month)
print(date_object.day)
PYTHON

Output

2019
4
13

Working with ‘time’ Class

Representing Time

A time object can be used to represent any valid time (hours, minutes and seconds).

Code

from datetime import time
time_object = time(11, 34, 56)
print(time_object)
PYTHON

Output

11:34:56

Attributes of Time Object

Code

from datetime import time
time_object = time(11, 34, 56)
print(time_object)
print(time_object.hour)
print(time_object.minute)
print(time_object.second)
PYTHON

Output

11:34:56
11
34
56

Working with ‘datetime’ Class

Datetime

The datetime class represents a valid date and time together.

Example - 1

Code

from datetime import datetime
date_time_obj = datetime(2018, 11, 28, 10, 15, 26)
print(date_time_obj.year)
print(date_time_obj.month)
print(date_time_obj.hour)
print(date_time_obj.minute)
PYTHON

Output

2018
11
10
15

Example - 2 It gives the current date and time

Code

import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
PYTHON

Output

2021-02-05 09:26:08.077473

DateTime object

Code

from datetime import datetime
date_time_obj = datetime(2018, 11, 28)
print(date_time_obj)
PYTHON

Output

2018-11-28 00:00:00

Formatting Datetime

The datetime classes have

strftime(format)
method to format the datetime into any required format like

  • mm/dd/yyyy
  • dd-mm-yyyy

    Format SpecifierMeaningExample
    %yYear without century as a zero-padded decimal number19, 20, ...
    %YYear with century as a decimal number2019, 2020, ...
    %bMonth as abbreviated nameJan, Feb, ...
    %BMonth as full nameJanuary, February
    %mMonth as a zero-padded decimal number01, 02, …, 12
    %dDay of the month as a zero-padded decimal number01, 02, …, 31
    %aWeekday as abbreviated nameSun, Mon, ...
    %AWeekday as full nameSunday, Monday, ...
    %HHour (24-hour clock) as a zero-padded decimal number00, 01, …, 23
    %IHour (12-hour clock) as a zero-padded decimal number01, 02, …, 12
    %pAM or PMAM, PM
    %MMinute as a zero-padded decimal number00, 01, …, 59
    %SSecond as a zero-padded decimal number00, 01, …, 59

Code

from datetime import datetime
now = datetime.now()
formatted_datetime_1 = now.strftime("%d %b %Y %I:%M:%S %p")
print(formatted_datetime_1)
formatted_datetime_2 = now.strftime("%d/%m/%Y, %H:%M:%S")
print(formatted_datetime_2)
PYTHON

Output

05 Feb 2021 09:26:50 AM
05/02/2021, 09:26:50

Parsing Datetime

The class method

strptime()
creates a datetime object from a given string representing date and time.

Code

from datetime import datetime
date_string = "28 November, 2018"
print(date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print(date_object)
PYTHON

Output

28 November, 2018
2018-11-28 00:00:00

Working with ‘timedelta’ Class

Timedelta object represents duration.

Example 1

Code

from datetime import timedelta
delta = timedelta(days=365, hours=4)
print(delta)
PYTHON

Output

365 days, 4:00:00

Example 2

Code

from datetime import timedelta, datetime
delta = timedelta(days=365)
current_datetime = datetime.now()
print(current_datetime)
next_year_datetime = current_datetime + delta
print(next_year_datetime)
PYTHON

Output

2021-02-05 09:28:30.239095
2022-02-05 09:28:30.239095

Calculating Time Difference

Code

import datetime
dt1 = datetime.datetime(2021, 2, 5)
dt2 = datetime.datetime(2022, 1, 1)
duration = dt2 - dt1
print(duration)
print(type(duration))
PYTHON

Output

330 days, 0:00:00
<class 'datetime.timedelta'>

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form