|
Getting your Trinity Audio player ready...
|
Time is everywhere in our life—whether it’s checking the current time, scheduling a meeting, or calculating someone’s age. Python provides powerful tools to work with dates and times, mainly through the datetime module.

In this post, we’ll go step by step from basics to advanced concepts with real-life examples.
1. Importing datetime Module
Python’s datetime module is the main toolkit for working with dates and times.
import datetime2. Getting Current Date and Time
You can get the current local date and time with:
import datetime
now = datetime.datetime.now()
print("Current Date and Time:", now)👉 Example Output:
Current Date and Time: 2025-08-17 14:45:30.123456
now()gives you both date and time.today()also works the same asnow().
3. Getting Only Date or Only Time
Sometimes, you only need the date or time separately.
import datetime
today = datetime.date.today()
print("Today's Date:", today)
time_now = datetime.datetime.now().time()
print("Current Time:", time_now)👉 Example Output:
Today's Date: 2025-08-17
Current Time: 14:45:30.123456
4. Accessing Year, Month, Day, Hour, Minute, Second
You can extract individual parts easily:
now = datetime.datetime.now()
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)5. Formatting Dates and Times (strftime)
Python allows formatting of date and time into human-readable strings.
now = datetime.datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted Date & Time:", formatted)👉 Useful Format Codes:
| Directive | Description | Example |
|---|---|---|
| %a | Weekday, short version | Wed |
| %A | Weekday, full version | Wednesday |
| %w | Weekday as a number 0-6, 0 is Sunday | 3 |
| %d | Day of month 01-31 | 31 |
| %b | Month name, short version | Jan |
| %B | Month name, full version | January |
| %m | Month as a number 01-12 | 01 |
| %y | Year, short version, without century | 23 |
| %Y | Year, full version | 2023 |
| %H | Hour 00-23 | 14 |
| %I | Hour 00-12 | 02 |
| %p | AM or PM | PM |
| %M | Minutes 00-59 | 45 |
| %S | Seconds 00-59 | 59 |
| %f | Microseconds 000000-999999 | 000123 |
| %z | UTC offset | +0530 |
| %Z | Timezone | IST |
| %j | Day number of year 001-366 | 365 |
| %U | Week number of year, Sunday as first day | 52 |
| %W | Week number of year, Monday as first day | 52 |
| %c | Local date and time | Wed Dec 31 14:45:59 2023 |
| %x | Local date | 12/31/23 |
| %X | Local time | 14:45:59 |
| %% | A literal % character | % |
👉 Output:
Formatted Date & Time: 17-08-2025 14:45:30
6. Parsing Strings into Date (strptime)
What if you have a date as a string? You can convert it into a datetime object:
date_string = "25-12-2025 10:30:00"
dt_object = datetime.datetime.strptime(date_string, "%d-%m-%Y %H:%M:%S")
print("Converted Date Object:", dt_object)👉 Output:
Converted Date Object: 2025-12-25 10:30:00
strftime()→ Stands for String Format Time. It converts a datetime object into a string (for displaying in a custom format).strptime()→ Stands for String Parse Time. It converts a string into a datetime object (for processing dates in Python).👉 Easy way to remember:
f= format (object → string),p= parse (string → object).
7. Timedelta (Working with Date Differences)
timedelta is used for date arithmetic (like yesterday, tomorrow, age calculation, etc.).
import datetime
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)👉 Example Output:
Yesterday: 2025-08-16
Tomorrow: 2025-08-18
Read More: File Handling in Python
Example: Age Calculator
import datetime
dob = datetime.date(1998, 5, 10) # Date of Birth
today = datetime.date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
print("Your Age is:", age)👉 Output:
Your Age is: 27
Explaination of below code:
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))today.year – dob.year → This gives the difference between the current year and the birth year
((today.month, today.day) < (dob.month, dob.day)) → This checks whether the person’s birthday has already occurred this year or not.
If the birthday hasn’t come yet, it returns True (which is 1 in Python).
If the birthday has already passed, it returns False (which is 0).
Subtracting this result ensures the age is calculated correctly.
Example:
Today = 17-08-2025
Date of Birth = 20-09-2000
Here, the birthday (20 Sept) hasn’t come yet in 2025 → condition is True → subtract 1.
So, 2025 – 2000 – 1 = 24 years old.
8. Working with Timezones (pytz)
Python’s datetime doesn’t handle timezones by itself. For that, use pytz.
import datetime
import pytz
utc_time = datetime.datetime.now(pytz.utc)
print("UTC Time:", utc_time)
india_time = utc_time.astimezone(pytz.timezone("Asia/Kolkata"))
print("Indian Time:", india_time)👉 Example Output:
UTC Time: 2025-08-17 09:15:30.123456+00:00
Indian Time: 2025-08-17 14:45:30.123456+05:30
9. Measuring Execution Time
You can also calculate how long a program takes to run.
import datetime
import time
start = datetime.datetime.now()
# some task
time.sleep(2)
end = datetime.datetime.now()
print("Execution Time:", end - start)👉 Output:
Execution Time: 0:00:02.000123
10. Real-Life Example: Reminder App
import datetime
import time
reminder_time = datetime.datetime.strptime("17-08-2025 15:00:00", "%d-%m-%Y %H:%M:%S")
print("Reminder set for:", reminder_time)
while True:
if datetime.datetime.now() >= reminder_time:
print("🔔 Time to attend the meeting!")
break
time.sleep(1)👉 Output:
Reminder set for: 2025-08-17 15:00:00
🔔 Time to attend the meeting!
Final Thoughts
- Use
datetime.now()to get current date and time. - Use
strftime()andstrptime()for formatting and parsing. - Use
timedeltafor calculations (like age, deadlines, schedules). - Use
pytzfor handling multiple timezones.
Mastering date and time in Python is essential for real-world applications like logging, scheduling, reminders, file management, and automation.
FAQs – Date and Time in Python
What is the difference between datetime.date, datetime.time, and datetime.datetime?
datetime.date→ Stores only the date (year, month, day).datetime.time→ Stores only the time (hour, minute, second, microsecond).datetime.datetime→ Stores both date and time together.
How can I format the date in Python?
Use strftime(). For example:
This prints the date in DD-MM-YYYY format.
How can I convert a string into a date in Python?
Use strptime(). For example:
Can I do date calculations in Python?
Yes! You can use timedelta. For example:
This will give the date 7 days from today.
What’s Next?
In the next post, we’ll learn about the JSON Module in Python