In this Python tutorial, we will learn how to use the datetime module to create dates and times, get the current date and time, access individual components, format and parse values, calculate time differences, and work with time zones.
Python datetime Module
Python’s built-in datetime module provides classes for working with dates, times, combined date-time values, durations, and time zones. Because it belongs to the Python standard library, you do not need to install a separate package.
The most commonly used classes are:
datetime.datefor a calendar date containing a year, month, and day.datetime.timefor a time of day containing hours, minutes, seconds, and microseconds.datetime.datetimefor a combined date and time.datetime.timedeltafor a duration or difference between two date-time values.datetime.timezonefor fixed-offset time-zone information.
Import the Python datetime Module
To import datetime module, use the following import statement.
import datetime
With this import style, include the module name when referring to a class or function, such as datetime.datetime.now().
You can also import individual classes when you want shorter names.
from datetime import date, datetime, time, timedelta, timezone
Get the Current Date and Time in Python
To get current time, use now() function as shown below.
Python Program
import datetime
#get current time
x = datetime.datetime.now()
print(x)
Output
2019-09-12 12:18:06.255164
The output contains the current local date and time in the format YYYY-MM-DD HH:MM:SS.microseconds. The exact value changes each time the program runs.
Use date.today() when only the current local date is required.
from datetime import date
today = date.today()
print(today)
Example Output
2026-07-27
Create a Python datetime Object
In datetime module, date is an object. You can create a datetime object by passing year, month, day, hour, minute, second and micro-second as arguments.
The syntax to create a datetime object is:
datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
The parameters year, month and day are mandatory while hour, minute, second, microsecond and timezone information tzinfo are optional. The optional parameters are by default 0.
In the following example, you can observe how the default values for the optional parameters take effect.
Python Program
import datetime
#create datetime object with year, month, day
x = datetime.datetime(2018, 5, 24)
print(x)
#create datetime object with year, month, day, hour
x = datetime.datetime(2018, 5, 24, 5)
print(x)
#create datetime object with year, month, day, hour, minute
x = datetime.datetime(2018, 5, 24, 5, 45)
print(x)
#create datetime object with year, month, day, hour, minute, second
x = datetime.datetime(2018, 5, 24, 5, 45, 34)
print(x)
#create datetime object with year, month, day, hour, minute, second, microsecond
x = datetime.datetime(2018, 5, 24, 5, 45, 34, 542136)
print(x)
Output
2018-05-24 00:00:00
2018-05-24 05:00:00
2018-05-24 05:45:00
2018-05-24 05:45:34
2018-05-24 05:45:34.542136
The constructor validates its arguments. For example, a month outside the range 1 through 12 or an invalid day for the selected month raises ValueError.
Create Python date and time Objects Separately
Use the date class when you need only a calendar date and the time class when you need only a time of day.
from datetime import date, time
release_date = date(2026, 7, 27)
start_time = time(9, 30, 15)
print(release_date)
print(start_time)
Output
2026-07-27
09:30:15
A date object does not store a time, and a time object does not store a calendar date. Use datetime.combine() to combine them.
from datetime import date, datetime, time
meeting_date = date(2026, 7, 27)
meeting_time = time(14, 45)
meeting = datetime.combine(meeting_date, meeting_time)
print(meeting)
Output
2026-07-27 14:45:00
Access Year, Month, Day, Hour, Minute, and Second
A datetime object exposes each date and time component through attributes.
from datetime import datetime
value = datetime(2026, 7, 27, 16, 25, 42, 123456)
print("Year:", value.year)
print("Month:", value.month)
print("Day:", value.day)
print("Hour:", value.hour)
print("Minute:", value.minute)
print("Second:", value.second)
print("Microsecond:", value.microsecond)
Output
Year: 2026
Month: 7
Day: 27
Hour: 16
Minute: 25
Second: 42
Microsecond: 123456
Use the date() and time() methods to extract complete date and time objects from a datetime value.
from datetime import datetime
value = datetime(2026, 7, 27, 16, 25)
print(value.date())
print(value.time())
Output
2026-07-27
16:25:00
Format Python datetime with strftime()
The strftime() method converts a date or time object into a formatted string. The format string contains directives beginning with %.
from datetime import datetime
value = datetime(2026, 7, 27, 18, 5, 9)
print(value.strftime("%Y-%m-%d"))
print(value.strftime("%d/%m/%Y"))
print(value.strftime("%B %d, %Y"))
print(value.strftime("%I:%M:%S %p"))
Output
2026-07-27
27/07/2026
July 27, 2026
06:05:09 PM
Common formatting directives include:
| Directive | Meaning | Example |
|---|---|---|
%Y | Four-digit year | 2026 |
%m | Month number | 07 |
%d | Day of the month | 27 |
%H | Hour using the 24-hour clock | 18 |
%I | Hour using the 12-hour clock | 06 |
%M | Minute | 05 |
%S | Second | 09 |
%p | AM or PM | PM |
%A | Full weekday name | Monday |
%B | Full month name | July |
Parse a Date String with strptime()
The datetime.strptime() method converts a string into a datetime object. The format must describe the input string exactly.
from datetime import datetime
text = "27-07-2026 14:30"
value = datetime.strptime(text, "%d-%m-%Y %H:%M")
print(value)
print(type(value))
Output
2026-07-27 14:30:00
<class 'datetime.datetime'>
If the string and format do not match, Python raises ValueError. Validate external input or handle this exception when parsing user-provided values.
Use ISO 8601 Date and Time Strings
The ISO 8601 format is commonly used in APIs, configuration files, logs, and databases. Python provides isoformat() and fromisoformat() for compatible strings.
from datetime import datetime
value = datetime(2026, 7, 27, 10, 15, 30)
text = value.isoformat()
restored = datetime.fromisoformat(text)
print(text)
print(restored)
Output
2026-07-27T10:15:30
2026-07-27 10:15:30
Add or Subtract Time with timedelta
A timedelta object represents a duration. Add it to or subtract it from a date or datetime object to move forward or backward in time.
from datetime import datetime, timedelta
start = datetime(2026, 7, 27, 9, 0)
next_week = start + timedelta(days=7)
earlier = start - timedelta(hours=2, minutes=30)
print(next_week)
print(earlier)
Output
2026-08-03 09:00:00
2026-07-27 06:30:00
You can specify durations using arguments such as weeks, days, hours, minutes, seconds, milliseconds, and microseconds.
Find the Difference Between Two Python datetime Values
Subtract one datetime value from another to obtain a timedelta. This is useful for calculating elapsed time, deadlines, session lengths, and countdowns.
from datetime import datetime
start = datetime(2026, 7, 27, 9, 15)
end = datetime(2026, 7, 29, 12, 45)
difference = end - start
print(difference)
print("Days:", difference.days)
print("Total seconds:", difference.total_seconds())
Output
2 days, 3:30:00
Days: 2
Total seconds: 185400.0
The days attribute contains only the whole-day portion. Use total_seconds() when you need the complete duration converted to seconds.
Compare Python Dates and Times
Date and time objects of compatible types can be compared with operators such as <, >, ==, <=, and >=.
from datetime import datetime
current = datetime(2026, 7, 27, 10, 0)
deadline = datetime(2026, 7, 30, 17, 0)
if current < deadline:
print("The deadline has not passed.")
else:
print("The deadline has passed.")
Output
The deadline has not passed.
Do not compare a timezone-aware datetime directly with a timezone-naive datetime. Convert both values to a consistent time-zone representation first.
Replace Components of a datetime Object
Python date and time objects are immutable. The replace() method returns a new object with selected components changed.
from datetime import datetime
original = datetime(2026, 7, 27, 9, 30)
updated = original.replace(hour=14, minute=0)
print(original)
print(updated)
Output
2026-07-27 09:30:00
2026-07-27 14:00:00
Work with UTC and Timezone-Aware datetime Objects
A naive datetime has no time-zone information. An aware datetime includes a tzinfo value and represents an unambiguous point in time.
Use datetime.now(timezone.utc) to obtain the current UTC date and time as an aware object.
from datetime import datetime, timezone
utc_now = datetime.now(timezone.utc)
print(utc_now)
print(utc_now.tzinfo)
The exact output varies, but it includes the UTC offset +00:00.
You can create and convert fixed-offset time zones with timezone and astimezone().
from datetime import datetime, timedelta, timezone
utc_value = datetime(2026, 7, 27, 6, 0, tzinfo=timezone.utc)
india_offset = timezone(timedelta(hours=5, minutes=30))
india_value = utc_value.astimezone(india_offset)
print(utc_value)
print(india_value)
Output
2026-07-27 06:00:00+00:00
2026-07-27 11:30:00+05:30
For named regional time zones and daylight-saving transitions, use the standard-library zoneinfo module.
from datetime import datetime
from zoneinfo import ZoneInfo
utc_value = datetime(2026, 7, 27, 6, 0, tzinfo=ZoneInfo("UTC"))
kolkata_value = utc_value.astimezone(ZoneInfo("Asia/Kolkata"))
print(kolkata_value)
Output
2026-07-27 11:30:00+05:30
Convert Unix Timestamps to Python datetime
A Unix timestamp represents elapsed seconds from the Unix epoch. Use datetime.fromtimestamp() for local time or pass timezone.utc to obtain an aware UTC value.
from datetime import datetime, timezone
timestamp = 0
local_value = datetime.fromtimestamp(timestamp)
utc_value = datetime.fromtimestamp(timestamp, timezone.utc)
print(local_value)
print(utc_value)
The first line depends on the computer’s local time zone. The UTC result is:
1970-01-01 00:00:00+00:00
Use the timestamp() method to convert a datetime object back to a Unix timestamp.
from datetime import datetime, timezone
value = datetime(1970, 1, 1, tzinfo=timezone.utc)
print(value.timestamp())
Output
0.0
Common Python datetime Errors
Invalid datetime Constructor Values
Invalid calendar values raise ValueError.
from datetime import datetime
try:
value = datetime(2026, 2, 30)
except ValueError as error:
print(error)
Output
day is out of range for month
Incorrect strptime() Format
The parsing format must match the input text, including separators and component order. For example, 27/07/2026 requires %d/%m/%Y, not %Y-%m-%d.
Naive and Aware datetime Comparison
Python raises TypeError when ordering comparisons mix a naive value with an aware value. Assign or convert time-zone information consistently before comparing them.
Python datetime Frequently Asked Questions
What is the difference between date, time, and datetime in Python?
date stores a year, month, and day. time stores a time of day. datetime combines both a calendar date and a time of day in one object.
How do I get only the current date in Python?
Call date.today(), or call datetime.now().date() when you already work with the datetime class.
How do I convert a string to datetime in Python?
Use datetime.strptime(text, format) for a custom input format. For a supported ISO 8601 string, use datetime.fromisoformat(text).
How do I calculate days between two dates in Python?
Subtract the earlier date or datetime object from the later one. The result is a timedelta; its days attribute contains the whole-day difference.
Should Python applications store dates in UTC?
For events representing exact moments, storing timezone-aware UTC values is usually safer because it avoids ambiguity across regions. Convert UTC values to a user’s local time zone when displaying them. Calendar-only values such as birthdays or due dates may instead be stored as date objects when no time zone is involved.
Python datetime Tutorial Summary
In this Python Tutorial, we learned how to import the Python datetime module, create date, time, and datetime objects, get the current date and time, access individual components, format and parse strings, calculate durations with timedelta, compare values, use Unix timestamps, and create timezone-aware date-time values.
TutorialKart.com