This Date and Time exercise aims to help Python developers to learn and practice DateTime-related frequently occurring problems. Here I am providing 10 date and time programs to help you in brushing up your coding skills. All questions are tested on Python 3. Knowledge of Date and time manipulation is necessary if you want to be a good Python developer.
This Python DateTime exercise include the following: –
- It contains 10 questions and solutions provided for each question.
- This coding exercise is nothing but Python Date and time assignments to solve, where you can solve and practice different dates and time programs and challenges.
It covers questions on the following topics:
- Working with dates and times in Python
- Functions available in the Python datetime module
- Convert and manipulate date and time in a specific format
- Dates and times arithmetic
When you complete each question, you get more familiar with the DateTime operations. Let us know if you have any alternative solutions. It will help other developers.
Use Online Code Editor to solve exercise questions.
Table of contents
- Exercise 1: Print current date and time in Python
- Exercise 2: Convert string into a datetime object
- Exercise 3: Subtract a week (7 days) from a given date in Python
- Exercise 4: Print a date in a the following format
- Exercise 5: Find the day of the week of a given date
- Exercise 6: Add a week (7 days) and 12 hours to a given date
- Exercise 7: Print current time in milliseconds
- Exercise 8: Convert the following datetime into a string
- Exercise 9: Calculate the date 4 months from the current date
- Exercise 10: Calculate number of days between two given dates
Exercise 1: Print current date and time in Python
See: Get Current Date and Time in Python
Show Solution
Use datetime
module
import datetime
# Print date and time
print(datetime.datetime.now())
# only time
print(datetime.datetime.now().time())
Solution 2 using time.strftime()
from time import gmtime, strftime
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
Exercise 2: Convert string into a datetime object
For example, You received the following date in string format. Please convert it into Python’s DateTime object.
Refer: Python String to DateTime
Given:
date_string = "Feb 25 2020 4:20PM"
Expected output:
2020-02-25 16:20:00
Show Solution
from datetime import datetime
date_string = "Feb 25 2020 4:20PM"
datetime_object = datetime.strptime(date_string, '%b %d %Y %I:%M%p')
print(datetime_object)
Exercise 3: Subtract a week (7 days) from a given date in Python
Refer: TimeDelta in Python
Given:
given_date = datetime(2020, 2, 25)
Expected output:
2020-02-18
Show Solution
from datetime import datetime, timedelta
given_date = datetime(2020, 2, 25)
print("Given date")
print(given_date)
days_to_subtract = 7
res_date = given_date - timedelta(days=days_to_subtract)
print("New Date")
print(res_date)
Exercise 4: Print a date in a the following format
Day_name Day_number Month_name Year
Refer: Python DateTime Format Using Strftime()
Given:
given_date = datetime(2020, 2, 25)
Expected output:
Tuesday 25 February 2020
Refer Date format codes for help
Show Solution
from datetime import datetime
given_date = datetime(2020, 2, 25)
print("Given date is")
print(given_date.strftime('%A %d %B %Y'))
Exercise 5: Find the day of the week of a given date
Given:
given_date = datetime(2020, 7, 26)
Expected output:
Sunday
Show Solution
Solution 1:
from datetime import datetime
given_date = datetime(2020, 7, 26)
# to get weekday as integer
print(given_date.today().weekday())
# To get the english name of the weekday
print(given_date.strftime('%A'))
Solution 2 using calendar module
import calendar
from datetime import datetime
given_date = datetime(2020, 7, 26)
weekday = calendar.day_name[given_date.weekday()]
print(weekday)
Exercise 6: Add a week (7 days) and 12 hours to a given date
Given:
# 2020-03-22 10:00:00
given_date = datetime(2020, 3, 22, 10, 0, 0)
Expected output:
2020-03-29 22:00:00
Show Solution
from datetime import datetime, timedelta
given_date = datetime(2020, 3, 22, 10, 00, 00)
print("Given date")
print(given_date)
days_to_add = 7
res_date = given_date + timedelta(days=days_to_add, hours=12)
print("New Date")
print(res_date)
Exercise 7: Print current time in milliseconds
Show Solution
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)
Exercise 8: Convert the following datetime into a string
Given:
given_date = datetime(2020, 2, 25)
Expected output:
"2020-02-25 00:00:00"
Show Solution
from datetime import datetime
given_date = datetime(2020, 2, 25)
string_date = given_date.strftime("%Y-%m-%d %H:%M:%S")
print(string_date)
Exercise 9: Calculate the date 4 months from the current date
Given:
# 2020-02-25
given_date = datetime(2020, 2, 25).date()
Expected output:
2020-06-25
Show Solution
Solution:
- We need to use the Python
dateutil
module’srelativedelta
. We can add 4 months into the given date using arelativedelta
. - The
relativedelta
is useful when we want to deal months with day 29, 30 31, It will properly adjust the days.
from datetime import datetime
from dateutil.relativedelta import relativedelta
# 2020-02-25
given_date = datetime(2020, 2, 25).date()
months_to_add = 4
new_date = given_date + relativedelta(months=+ months_to_add)
print(new_date)
Exercise 10: Calculate number of days between two given dates
Given:
# 2020-02-25
date_1 = datetime(2020, 2, 25)
# 2020-09-17
date_2 = datetime(2020, 9, 17)
Expected output:
205 days
Show Solution
from datetime import datetime
# 2020-02-25
date_1 = datetime(2020, 2, 25).date()
# 2020-09-17
date_2 = datetime(2020, 9, 17).date()
delta = None
if date_1 > date_2:
print("date_1 is greater")
delta = date_1 - date_2
else:
print("date_2 is greater")
delta = date_2 - date_1
print("Difference is", delta.days, "days")