- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
Introduction
Welcome to our comprehensive guide on Python’s datetime module! In the world of programming, handling dates and times is a common requirement.
Features
The datetime module in Python boasts a range of features that make it an indispensable tool for working with date and time data:
- Precise date and time representation.
- Time zone awareness for handling time differences.
- Arithmetic operations on dates and times.
- Formatting and parsing of date and time strings.
- Support for both Gregorian and Julian calendar systems.
Different Functions of the datetime Module
- datetime.now() – Current Date and Time:
Returns the current date and time.
import datetime
current_datetime = datetime.datetime.now()
print(current_datetime)
# Output
2023-08-14 10:15:30.123456
2. datetime.combine() – Combine Date and Time:
Combines a date and a time into a single datetime object.
import datetime
date = datetime.date(2023, 8, 14)
time = datetime.time(10, 30)
combined_datetime = datetime.datetime.combine(date, time)
print(combined_datetime)
# Output
2023-08-14 10:30:00
3. datetime.strptime() – String to Datetime:
Converts a string to a datetime object based on a specified format.
import datetime
date_string = '2023-08-14'
formatted_date = datetime.datetime.strptime(date_string, '%Y-%m-%d')
print(formatted_date)
# Output
2023-08-14 00:00:00
Common Format Codes
| Code | Meaning |
|---|---|
%Y | Year (2025) |
%y | Year (25) |
%m | Month (01-12) |
%B | Month (full name) |
%d | Day (01-31) |
%A | Weekday (full name) |
%H | Hour (24 hr) |
%I | Hour (12 hr) |
%M | Minute |
%S | Second |
4. datetime.strftime() – Datetime to String:
Formats a datetime object as a string according to a given format.
import datetime
current_datetime = datetime.datetime.now()
formatted_datetime = current_datetime.strftime('%Y-%m-%d %H:%M:%S')
print(formatted_datetime)
# Output
2023-08-14 10:15:30
5. timedelta() – Time Interval:
Represents a duration of time, supporting arithmetic operations with datetime objects.
import datetime
delta = datetime.timedelta(days=5, hours=3)
future_date = datetime.datetime.now() + delta
print(future_date)
# Output
2023-08-19 13:15:30.123456
6. datetime.date() – Extract Date:
Extracts the date portion from a datetime object.
import datetime
current_datetime = datetime.datetime.now()
date_part = current_datetime.date()
print(date_part)
# Output
2023-08-14
7. datetime.time() – Extract Time:
Extracts the time portion from a datetime object.
import datetime
current_datetime = datetime.datetime.now()
time_part = current_datetime.time()
print(time_part)
# Output
10:15:30.123456
8. datetime.replace() – Replace Components:
Creates a new datetime object by replacing specific components.
import datetime
current_datetime = datetime.datetime.now()
modified_datetime = current_datetime.replace(hour=12, minute=0)
print(modified_datetime)
# Output
2023-08-14 12:00:30.123456
9. datetime.weekday() – Weekday Index:
Returns the index of the weekday (0 for Monday, 6 for Sunday).
import datetime
current_datetime = datetime.datetime.now()
weekday_index = current_datetime.weekday()
print(weekday_index)
# Output
6
10. datetime.isoweekday() – ISO Weekday:
Returns the ISO weekday (1 for Monday, 7 for Sunday).
import datetime
current_datetime = datetime.datetime.now()
iso_weekday = current_datetime.isoweekday()
print(iso_weekday)
# Output
7
11. datetime.timestamp() – Unix Timestamp:
Returns the Unix timestamp (the number of seconds since January 1, 1970).
import datetime
current_datetime = datetime.datetime.now()
timestamp = current_datetime.timestamp()
print(timestamp)
# Output
1673256930.123456
12. datetime.astimezone() – Timezone Conversion:
Converts a datetime object to a different timezone.
import datetime, pytz
current_datetime = datetime.datetime.now()
timezone = pytz.timezone('America/New_York')
converted_datetime = current_datetime.astimezone(timezone)
print(converted_datetime)
# Output
2023-08-14 06:15:30.123456-04:00
13. datetime.utcoffset() – UTC Offset:
Returns the UTC offset of a datetime object.
import datetime, pytz
current_datetime = datetime.datetime.now()
utc_offset = current_datetime.utcoffset()
print(utc_offset)
# Output
3:00:00
14. datetime.timedelta.total_seconds() – Total Seconds:
Returns the total number of seconds in a timedelta object.
import datetime
delta = datetime.timedelta(days=2, hours=5)
total_seconds = delta.total_seconds()
print(total_seconds)
# Output
189600.0
15. datetime.fromtimestamp() – Datetime from Timestamp:
Creates a datetime object from a Unix timestamp.
import datetime
timestamp = 1673256930.123456
converted_datetime = datetime.datetime.fromtimestamp(timestamp)
print(converted_datetime)
# Output
2023-08-09 10:15:30.123456