Date and Time in Python

Introduction

In this article you will learn how to work with date and time in Python 3.

Current time

Create a file current_time.py with the following contents

import datetime current_time = datetime.datetime.now() print(f"Now: {current_time}") # Hour, minute and second separately print(f"\nHour: {now.hour}" f"\nMinute: {now.minute}" f"\nSecond: {now.second}" ) # Year, month and day separately print(f"\nYear: {now.year}" f"\nMonth: {now.month}" f"\nDay: {now.day}" )

python current_time.py

2026-11-17 21:23:22

Now: 2026-11-17 21:23:22.185141 Hour: 09 Minute: 23 Second: 22 Year: 2026 Month: 11 Day: 17

2025-11-18 03:23:222026-11-17 21:23:22

Today's date

Create a file today.py with the following contents

import datetime today = datetime.date.today() print(f"Today: {today}")

python today.py

Today: 2026-11-17

Working with time in the standard library

Create a file date_time.py and copy the code from the examples into it.

You can run the file with the command python3 date_time.py

import datetime # DATE d = datetime.date(2020, 11, 23) print(d) tday = datetime.date.today() print(tday) print(tday.year) print(tday.month) print(tday.day) # Monday is 0 Sunday is 6 print(tday.weekday()) # Monday is 1 Sunday is 7 print(tday.isoweekday()) tdelta = datetime.timedelta(days=7) print(tday + tdelta) print(tday - tdelta) # date2 = date1 + timedelta # timedelta = date1 + date2 bday = datetime.date(2021, 9, 21) till_bday = bday - tday print(till_bday.days) print(till_bday.total_seconds()) # TIME t = datetime.time(9, 30, 45, 100000) print(t.hour) # DATETIME dt = datetime.datetime(2020, 11, 23, 12, 42, 30, 100000) print(dt.time()) print(dt.year) tdelta = datetime.timedelta(days=7) print(dt + tdelta) dt_today = datetime.datetime.today() dt_now = datetime.datetime.now() dt_utcnow = datetime.datetime.utcnow() print(dt_today) print(dt_now) print(dt_utcnow)

Working with time in the pytz library

Article author: Andrei Olegovich

Banner image