Python datetime

1) Import and Print Current Date

Write Python code to import datetime and print today’s date.


2) Current Time

Print the current time (hours:minutes:seconds).


3) Current Date & Time

Print the full current date and time (using datetime.now()).


4) Year, Month, Day

Extract and print year, month, and day from the current date.


5) Hour, Minute, Second

Extract and print hour, minute, and second from the current time.


6) Create Specific Date

Create a date object for:

and print it.


7) Format Date

Format today’s date as:

Example:


8) Format Date/Time

Format current date/time like:


9) Add Days

Ask user for a number n. Add n days to today’s date and print.


10) Subtract Days

Ask user for a number n. Subtract n days from today’s date and print.


11) Days Until New Year

Compute and print how many days are left until:


12) Difference Between Dates

Ask user for two dates and print the difference in days between them.


13) Convert String to Date

Ask for a date as string "YYYY-MM-DD" and convert it to a date object.


14) Date to String

Convert a datetime object to string in format:

Example:


15) Create Time Only

Create a time object for 14:30:15 and print.


16) Weekday of a Date

Ask for a date and print weekday name (e.g., Monday, Tuesday).


17) Timer (Elapsed Seconds)

Record start time, wait (e.g., sleep 2 seconds using time.sleep()), record end time, and print elapsed seconds.


18) Timestamp to Date

Convert a UNIX timestamp (e.g., 1609459200) to a readable date.


19) Date Arithmetic Loop

Print the next 7 dates (tomorrow, day after, …) starting from today.


20) Age Calculator

Ask for birth date; compute and print age in years.


🧠 Concepts Practiced

Task
Key Module/Method

Today’s date

datetime.date.today()

Current datetime

datetime.datetime.now()

Formatting

.strftime()

Parsing from string

datetime.datetime.strptime()

Adding/subtracting dates

timedelta

Date difference

date2 - date1


📝 Example Code Snippets

Current date/time

Formatting

Add days

Convert string to date

Day difference


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated