-
Hajipur, Bihar, 844101
Python has a built-in module called datetime
to work with dates and times.
To use it, you must import the module:
import datetime
import datetime
now = datetime.datetime.now()
print(now)
today = datetime.date.today()
print(today)
current_time = datetime.datetime.now().time()
print(current_time)
d = datetime.datetime(2023, 5, 17)
print(d)
now = datetime.datetime.now()
print(now.year)
print(now.month)
print(now.day)
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d")) # 2025-06-21
print(now.strftime("%A")) # Friday
print(now.strftime("%I:%M %p")) # 05:30 PM
Common format codes:
Code | Meaning |
---|---|
%Y |
Year |
%m |
Month (01–12) |
%d |
Day |
%H |
Hour (00–23) |
%I |
Hour (01–12) |
%M |
Minute |
%p |
AM or PM |
%A |
Weekday name |
from datetime import timedelta, datetime
today = datetime.now()
future = today + timedelta(days=10)
past = today - timedelta(days=5)
print(future)
print(past)
print(datetime.now().isoformat())
Get today’s date
Format it into DD-MM-YYYY
Add 7 days to current date
Extract time only from current timestamp
Q1. Write a Python program to print the current date and time using datetime.now()
.
Q2. Write a Python program to show only the year from today’s date.
Q3. Write a Python program to format today’s date as DD/MM/YYYY
.
Q4. Write a Python program to print the current time in HH:MM AM/PM
format.
Q5. Write a Python program to create a datetime
object for your birthday.
Q6. Write a Python program to add 15 days to the current date using timedelta
.
Q7. Write a Python program to subtract 7 days from today’s date using timedelta
.
Q8. Write a Python program to show the weekday name for today’s date (e.g., "Monday").
Q9. Write a Python program to print only the time from datetime.now()
.
Q10. Write a Python program to display the current date in ISO format using .isoformat()
.
Q1: Which module is used for date and time in Python?
Q2: What does datetime.now() return?
Q3: How do you create a custom date?
Q4: What will now.strftime("%A") return?
Q5: Which format code gives the year?
Q6: What does timedelta(days=5) do?
Q7: Which method gives today's date only?
Q8: How do you extract just the time?
Q9: What does %p format return in strftime?
Q10: What will now.strftime("%I:%M %p") show?