Python datetime Module
Python’s built-in datetime
module allows you to work with dates, times, and timedeltas easily.
To use it:
import datetime
1. Get Current Date and Time
import datetime
now = datetime.datetime.now()
print(now)
Output:
2025-06-16 06:30:12.123456
Explanation:datetime.now()
returns the current local date and time with microseconds.
2. Get Only Date or Time
import datetime
today = datetime.date.today()
print("Date:", today)
now = datetime.datetime.now()
print("Time:", now.time())
Output:
Date: 2025-06-16
Time: 06:30:12.123456
Explanation:
date.today()
returns the current date.now.time()
extracts only the time from adatetime
object.
3. Create a Custom Date or Time
import datetime
birthday = datetime.date(1990, 5, 10)
print(birthday)
Output:
1990-05-10
Explanation:
Creates a date object with year, month, day.
4. Get Day, Month, Year, Weekday
import datetime
d = datetime.date(2025, 6, 16)
print("Day:", d.day)
print("Month:", d.month)
print("Year:", d.year)
print("Weekday:", d.weekday()) # Monday = 0
Output:
Day: 16
Month: 6
Year: 2025
Weekday: 0
5. Format Dates with strftime()
import datetime
now = datetime.datetime.now()
print(now.strftime("%d/%m/%Y"))
print(now.strftime("%A, %B %d, %Y"))
Output :
16/06/2025
Monday, June 16, 2025
Explanation:
%d
= day,%m
= month,%Y
= year%A
= weekday name,%B
= month name
6. Parse Strings into Dates with strptime()
import datetime
date_str = "21-06-2025"
date_obj = datetime.datetime.strptime(date_str, "%d-%m-%Y")
print(date_obj)
Output:
2025-06-21 00:00:00
Explanation:
Converts a date string into a datetime
object.
7. Timedelta: Date Arithmetic
import datetime
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
print("Tomorrow:", tomorrow)
past = today - datetime.timedelta(days=7)
print("7 days ago:", past)
Output:
Tomorrow: 2025-06-17
7 days ago: 2025-06-09
Explanation:timedelta
represents a time difference. You can add or subtract days, hours, etc.
8. Get UTC Time
import datetime
utc_now = datetime.datetime.utcnow()
print(utc_now)
Output:
2025-06-16 01:00:12.345678
Explanation:
Returns the current UTC date and time.
9. Pause Execution with time.sleep()
import time
print("Wait 3 seconds...")
time.sleep(3)
print("Done!")
Output:
Wait 3 seconds...
Done!
Explanation:time.sleep(seconds)
pauses the program for the given number of seconds.
Summary Table
Function/Feature | Description |
---|---|
datetime.now() | Current date and time |
date.today() | Current date only |
datetime.time() | Extracts time |
datetime(year, m, d) | Create a specific date |
strftime() | Format date to string |
strptime() | Parse string to date |
timedelta(days=n) | Add/subtract time intervals |
datetime.utcnow() | Get UTC time |
time.sleep(n) | Pause execution |