Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Get the Current Date and Time in Python

Use the datetime, time and calendar modules, and pytz for time zones.

How-To Guides2 min read5 screenshots

The datetime module

Current date and time

import datetime

# Get the current date and time
now = datetime.datetime.now()
print("Current date and time:", now)
Current date and time with datetime

Format it

formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date and time:", formatted_now)

Date only

today = datetime.date.today()
print("Current date:", today)
The current date

Time only

current_time = datetime.datetime.now().time()
print("Current time:", current_time)

The time module

Seconds since the Epoch (January 1, 1970)

import time
current_time_seconds = time.time()
print("Current time in seconds since the Epoch:", current_time_seconds)
Time in seconds

Make it readable

readable_time = time.ctime(current_time_seconds)
print("Readable current time:", readable_time)

UTC and local time

gmtime = time.gmtime(current_time_seconds)
localtime = time.localtime(current_time_seconds)
print("GMT time:", gmtime)
print("Local time:", localtime)

The calendar module

Get the year, month and day:

import datetime

now = datetime.datetime.now()
print("Current year:", now.year)
print("Current month:", now.month)
print("Current day:", now.day)
Year, month and day

The calendar module can print a month:

import calendar
print(calendar.month(now.year, now.month))

Time zones with pytz

Install the library:

pip install pytz

Get the time in a given zone:

import datetime
import pytz

tz = pytz.timezone("America/New_York")
print(datetime.datetime.now(tz))
Time in a given time zone

Python 3.9 and later also has the built-in zoneinfo module, which does the same without a package:

from zoneinfo import ZoneInfo
import datetime
print(datetime.datetime.now(ZoneInfo("Europe/London")))

Common format codes

CodeMeaning
%YYear with 4 digits
%mMonth number
%dDay of the month
%HHour (24-hour clock)
%MMinute
%SSecond
%ADay name

Quick recap

  • datetime.datetime.now() gives the current date and time.
  • strftime() formats it.
  • Use pytz or zoneinfo for time zones.