Python DateTime Guide: Working with Date and Time in Python (With Examples)
What is date and time data?
Date and time data refers to information that captures temporal aspects of events, such as when something occurred, how long it lasted, or when it is scheduled to happen. This type of data can represent a specific day, an exact moment in time, or even a recurring pattern across hours, days, months, or years.
In Python, date and time are commonly represented using structured objects like date
, time
, and datetime
. These objects make it possible to work with precise values such as the day of the week, hour of the day, or elapsed duration. For example:
- A
date
object may store a birthday:2025-05-02
- A
time
object may capture a scheduled meeting time:14:30:00
- A
datetime
object may combine both:2025-05-02 14:30:00
How to Transform Tables with SQL
Practice more SQL in this course that covers how to manipulate and transform data.Try it for freeWhere is the date time data used
Date and time data appear across nearly every industry:
Web and mobile development: Timestamps track user activity, form submissions, or content updates.
Data analysis: Time-series datasets help identify trends over hours, days, or years.
Finance and trading: Millisecond precision timestamps record transactions in global markets.
Healthcare systems: Scheduling, medical logs, and patient history rely on accurate temporal data.
IoT and embedded systems: Devices frequently log readings or status reports over time.
Scheduling systems: Apps depend on accurate time handling to manage appointments, tasks, or reminders.
Understanding and manipulating this data accurately ensures programs behave reliably, especially when dealing with deadlines, logging, or calculations that depend on the passage of time.
Understanding how Python represents date and time internally begins with exploring the built-in datetime
module.
What is the datetime
module in Python
Python’s datetime
module is the primary toolkit for working with dates and times. It provides classes that allow representation, manipulation, and formatting of date/time values in structured and meaningful ways. To begin using datetime
, the module must be imported. Here’s a basic example illustrating the use of the datetime
module:
import datetimecurrent_time = datetime.datetime.now()print("Current Date and Time:", current_time)
One of the possible outputs of this code will be:
Current Date and Time: 2025-05-02 13:26:54.795047
Note: The output will change based on the current date and time.
This example uses the datetime
class within the datetime
module to fetch the current date and time. The module provides several key classes, each suited for different kinds of temporal data. The datetime
module includes four main classes:
date
: Represents a calendar datetime
: Represents a time of daydatetime
: Combines date and timetimedelta
: Represents a duration or difference
Let us explore each of these classes.
Python date
class
It represents a calendar date (year, month, and day). The syntax of the date
class is as follows:
datetime.date(year, month, day)
Parameters:
year
: Integer (e.g., 2025)month
: Integer from 1 to 12day
: Integer from 1 to 31 (depending on the month)
Return value:
- It returns a
date
object.
Example:
from datetime import dated = date(2025, 5, 2)print(d)
Output:
2025-05-02
The example creates a date object representing May 2, 2025.
Some standard methods of the date
class are as follows:
Method | Description |
---|---|
.year |
Returns the year |
.month |
Returns the month |
.day |
Returns the day |
.weekday() |
Returns the day of the week (0 = Mon) |
.isoformat() |
Returns ISO format string |
.today() |
Returns current local date |
Python time
class
It represents a time of day (hour, minute, second, microsecond). The syntax of the time
class is as follows:
datetime.time(hour=0, minute=0, second=0, microsecond=0)
Parameters:
hour
: Integer from 0 to 23minute
: Integer from 0 to 59second
: Integer from 0 to 59microsecond
: Integer from 0 to 999999
Return value:
- It returns a
time
object.
Example:
from datetime import timet = time(14, 30)print(t)
Output:
14:30:00
Creates a time object representing 2:30 pm. Some standard methods of the time
class are as listed here:
Method | Description |
---|---|
.hour |
Returns the hour |
.minute |
Returns the minutes |
.second |
Returns the seconds |
.microsecond |
Returns the microseconds |
.isoformat() |
Returns ISO format string |
Python datetime
class
Combines both date and time into a single object. The syntax of the datetime
class is as follows:
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0)
Parameters:
year
: Integer (e.g., 2025)month
: Integer from 1 to 12day
: Integer from 1 to 31 (depending on the month)hour
: Integer from 0 to 23minute
: Integer from 0 to 59second
: Integer from 0 to 59microsecond
: Integer from 0 to 999999
Note: The parameters of the
datetime
class are similar to thedate
andtime
class combined.
Return value:
- It returns a
datetime
object.
Example:
from datetime import datetimedt = datetime(2025, 5, 2, 14, 30)print(dt)
Output:
2025-05-02 14:30:00
This example creates a datetime object for May 2, 2025, at 2:30 pm.
Some standard methods of the datetime
class are as follows:
Method | Description |
---|---|
.year , .month , .day |
Extracts date parts |
.hour , .minute , .second |
Extracts time parts |
.now() |
Returns current local datetime |
.today() |
Returns current local date and time |
.utcnow() |
Returns current UTC datetime |
.isoformat() |
Returns ISO 8601 formatted string |
.strftime(fmt) |
Returns formatted datetime string |
.date() |
Extracts date object from datetime |
.time() |
Extracts time object from datetime |
Python timedelta
class
The timedelta
class represents a duration, i.e., the difference between two dates or times. It performs arithmetic with date
, time
, or datetime
objects. The syntax of the timedelta
class is as follows:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Parameters:
days
: Number of days (can be negative)seconds
: Number of seconds (0 to 86399)microseconds
: Number of microseconds (0 to 999999)milliseconds
: Converts to microseconds internallyminutes
: Converts to seconds internallyhours
: Converts to seconds internallyweeks
: Converts to days internally
Each parameter is optional and defaults to 0
.
Return value:
- It returns a
timedelta
object representing a duration.
Example:
from datetime import datetime, timedeltastart = datetime(2025, 5, 2)duration = timedelta(days=10)end = start + durationprint("End date:", end)
Output:
End date: 2025-05-12 00:00:00
This example adds 10 days to a given date (May 2, 2025
). The timedelta
object encapsulates the duration, and arithmetic is performed using the +
operator.
Common operations of the timedelta
class include:
Operation | Description |
---|---|
dt1 + timedelta |
Adds a duration to a datetime |
dt2 - timedelta |
Subtracts a duration from a datetime |
dt2 – dt1 |
Returns a timedelta representing time difference |
td.days |
Number of complete days in the duration |
td.total_seconds() |
Total duration in seconds (float) |
-td |
Negates the duration |
Example:
date1 = datetime(2025, 5, 12)date2 = datetime(2025, 5, 2)difference = date1 - date2print("Difference in days:", difference.days)
Output:
Difference in days: 10
Subtracting two datetime objects returns a timedelta
, from which the number of days can be accessed using .days
.
Working with dates and times often requires converting between objects and human-readable strings. The next step involves understanding how to format and parse datetime values efficiently.
Formatting and parsing datetime strings
Formatting converts datetime
objects into strings for display, logging, or exporting data. Parsing does the reverse—transforming strings into structured datetime
objects. Python’s datetime
module provides two essential methods for these tasks: strftime()
for formatting and strptime()
for parsing.
Formatting dates with strftime()
The strftime()
method generates a string representation of a date
, time
, or datetime
object using a specified format. The syntax of the strftime()
method is:
datetime_object.strftime(format_string)
Parameters:
format_string
: A string containing format codes (e.g.,%Y
,%m
,%d
)
Return value:
- A formatted string representing the datetime.
Example:
from datetime import datetimenow = datetime(2025, 5, 2, 14, 30)formatted = now.strftime("%Y-%m-%d %H:%M:%S")print(formatted)
Output:
2025-05-02 14:30:00
The datetime is formatted into a commonly used year-month-day hour:minute:second format.
Parsing dates with strptime()
The strptime()
method parses a string into a datetime
object, using a defined format string to interpret the structure. It has the following syntax:
datetime.strptime(date_string, format_string)
Parameters:
date_string
: The input string to be parsedformat_string
: Format specification matching the string
Return value:
- A
datetime
object.
Example:
from datetime import datetimedate_str = "2025-05-02 14:30:00"parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")print(parsed)
Output:
2025-05-02 14:30:00
This converts a string into a proper datetime
object using a format that mirrors the input.
Common strftime()
and strptime()
format codes
Here’s a reference table of commonly used strftime
/strptime
format codes:
Code | Meaning | Example Output |
---|---|---|
%Y |
Four-digit year | 2025 |
%y |
Two-digit year | 25 |
%m |
Month (01–12) | 05 |
%B |
Full month name | May |
%d |
Day of the month (01–31) | 02 |
%A |
Full weekday name | Friday |
%H |
Hour (00–23) | 14 |
%I |
Hour (01–12, AM/PM) | 02 |
%p |
AM/PM | PM |
%M |
Minute (00–59) | 30 |
%S |
Second (00–59) | 00 |
%f |
Microsecond (000000–999999) | 000000 |
%Z |
Time zone name | UTC (if set) |
%j |
Day of the year (001–366) | 122 |
%W |
Week number (Monday-start) | 17 |
While formatting and parsing ensure data is human-readable and machine-friendly, real-world applications often involve working across multiple time zones, making timezone handling an essential skill.
Handling time zones using the pytz
library
Python’s standard DateTime
objects are flexible but can be ambiguous about time zones. Applications that operate across regions, such as web apps, global APIs, or scheduling platforms, must account for time zone differences to maintain accuracy.
Python’s datetime
objects are classified as either naive or aware:
- Naive: Does not contain time zone information. It assumes local time but is ambiguous.
- Aware: Contains time zone data and can perform accurate conversions and comparisons.
Example:
from datetime import datetimenaive = datetime.now()print("Naive:", naive)
Output:
Naive: 2025-05-02 14:30:00
The object here does not have a time zone associated with it, so it cannot be reliably compared with times from other zones.
This is where the pytz
library comes into play. The pytz
library provides access to the Olson time zone database, making it easier to assign and convert time zones. Run the following command in the terminal to install it:
pip install pytz
Example:
from datetime import datetimeimport pytzutc = pytz.utclocal = pytz.timezone("Asia/Kolkata")naive_dt = datetime(2025, 5, 2, 14, 30)aware_utc = utc.localize(naive_dt)converted = aware_utc.astimezone(local)print("UTC Time:", aware_utc)print("Kolkata Time:", converted)
Output:
UTC Time: 2025-05-02 14:30:00+00:00Kolkata Time: 2025-05-02 20:00:00+05:30
A naive datetime is localized to UTC and then converted to another timezone (Asia/Kolkata
) using .astimezone()
. Once a datetime
object is time zone-aware, converting it to another zone is straightforward:
eastern = pytz.timezone("US/Eastern")tokyo = pytz.timezone("Asia/Tokyo")dt_eastern = eastern.localize(datetime(2025, 5, 2, 9, 0))dt_tokyo = dt_eastern.astimezone(tokyo)print("Eastern Time:", dt_eastern)print("Tokyo Time:", dt_tokyo)
Using zoneinfo
for Python 3.9+
Starting with Python 3.9, the zoneinfo
module was introduced as a modern, built-in alternative to pytz
. Here’s how it can be used:
from datetime import datetimefrom zoneinfo import ZoneInfodt = datetime(2025, 5, 2, 14, 30, tzinfo=ZoneInfo("UTC"))converted = dt.astimezone(ZoneInfo("America/New_York"))print("UTC:", dt)print("New York:", converted)
Output:
UTC: 2025-05-02 14:30:00+00:00New York: 2025-05-02 10:30:00-04:00
The benefits of using zoneinfo
are as listed here:
- No external installation required
- Part of Python’s standard library (3.9+)
- Uses the IANA time zone database directly
Conclusion
Working with date and time data in Python is a fundamental skill that supports countless real-world applications—from tracking user activity to scheduling automated tasks. Python’s datetime
module and tools like pytz
and zoneinfo
provide everything needed to represent, manipulate, format, and convert temporal data accurately. Handling timestamps and durations becomes precise and intuitive with a clear understanding of classes like date
, time
, datetime
, and timedelta
.
To explore more hands-on coding with Python’s date and time features, check out Codecademy’s Learn Python 3 course, which covers essential programming concepts.
Frequently asked questions
1. How to convert a string in YYYY-MM-DD
format to a datetime
object in Python?
Use the strptime()
method from the datetime
class:
from datetime import datetimedate_str = "2025-05-02"dt = datetime.strptime(date_str, "%Y-%m-%d")print(dt) # Output: 2025-05-02 00:00:00
2. What is the use of datetime()
in Python?
The datetime()
constructor creates a datetime
object by combining date and time components. It belongs to the datetime
class and accepts parameters like year, month, day, hour, minute, etc.
from datetime import datetimedt = datetime(2025, 5, 2, 14, 30)print(dt) # Output: 2025-05-02 14:30:00
3. When to use datetime
?
The datetime
class is ideal when both the date and time need to be tracked together, such as in timestamps, logging events, scheduling tasks, or storing full calendar events in applications.
4. How to compare two dates in Python?
Two datetime
or date
objects can be compared directly using comparison operators like ==
, <
, >
, etc.
from datetime import dated1 = date(2025, 5, 2)d2 = date(2025, 5, 10)print(d1 < d2) # Output: True
5. What is a timestamp in Python?
A timestamp is a floating-point number representing the number of seconds since the Unix epoch (January 1, 1970, UTC). It can be obtained using datetime.timestamp()
and converted using datetime.fromtimestamp()
.
from datetime import datetimenow = datetime.now()ts = now.timestamp()print(ts) # Output: 1746188512.123456 (example)
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
How to Format a Date in JavaScript
Learn how to format dates in JavaScript using built-in methods and custom techniques. Explore JavaScript date format options for better control over date representation. - Article
How to Build a Python Script: A Beginner’s Guide to Python Scripting
Learn scripting and how to build Python scripts from scratch. Set up your environment, structure your code, run the script, and explore real examples with tips to get started. - Article
Python Syntax Guide for Beginners
Learn Python syntax with this beginner-friendly guide. Understand Python indentation, print statements, variables, comments, user input, and more with examples.
Learn more on Codecademy
- Course
How to Transform Tables with SQL
Practice more SQL in this course that covers how to manipulate and transform data.With CertificateIntermediate2 hours - Free course
Learn C#: References
Unlock the power of references, an essential aspect of object-oriented programming in C#.Beginner Friendly3 hours - Free course
Managing Your Time So It Doesn't Manage You
Take control of your time with effective management techniques. Learn to block time stealers, use to-do lists and schedules, and regularly review plans for better productivity.Beginner Friendly< 1 hour