python problem on datetime

Python Problems on Datetime solution

February 16, 20247 min read

Problem 1: Display the Current Date and Time

Problem Description: Write a Python program that uses the datetime library to display the current date and time in the format YYYY-MM-DD HH:MM:SS.

Sample Input: No input required.

Expected Output:2023-04-05 14:30:45 (Note: Output will vary based on the current date and time.)

Solution:

from datetime import datetime

# Get the current date and time
now = datetime.now()

# Format the date and time
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")

print("Current date and time:", formatted_now)

This solution demonstrates how to use datetime.now() to retrieve the current date and time, and strftime() to format it.

Problem 2: Calculate Age

Problem Description: Create a program that calculates a person's age based on their birthdate entered by the user. The birthdate should be input in the format YYYY-MM-DD.

Sample Input:2000-01-01

Expected Output:23 years old (Note: Output will vary based on the current date and the input date.)

Solution:

from datetime import datetime

# User inputs their birthdate
birthdate_input = input("Enter your birthdate (YYYY-MM-DD): ")
birthdate = datetime.strptime(birthdate_input, "%Y-%m-%d")

# Calculate age
today = datetime.now()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))

print(f"You are {age} years old.")

This solution uses strptime() to convert the user input into a datetime object and arithmetic to calculate the age.

Problem 3: Days Until New Year

Problem Description: Write a Python script that calculates the number of days from the current date until the next New Year's Day.

Sample Input: No input required.

Expected Output:88 days until New Year (Note: Output will vary based on the current date.)

Solution:

from datetime import datetime, timedelta

# Get today's date
today = datetime.now()

# Calculate the next New Year's Day
next_new_year = datetime(today.year + 1, 1, 1)

# Calculate the difference
days_until_new_year = (next_new_year - today).days

print(f"{days_until_new_year} days until New Year")

This solution calculates the difference in days between today and the next New Year's Day using datetime arithmetic.

Problem 4: Weekday of Birth

Problem Description: Ask the user to enter their birthdate in the format YYYY-MM-DD, and then display the day of the week they were born on.

Sample Input:2000-01-01

Expected Output:Saturday

Solution:

from datetime import datetime

# User inputs their birthdate
birthdate_input = input("Enter your birthdate (YYYY-MM-DD): ")
birthdate = datetime.strptime(birthdate_input, "%Y-%m-%d")

# Get the day of the week
day_of_week = birthdate.strftime("%A")

print(f"You were born on a {day_of_week}.")

This solution uses strftime("%A") to format the birthdate as the full weekday name.

Problem 5: Adding Days to a Date

Problem Description: Write a Python program that asks the user to enter a date in the format YYYY-MM-DD and a number of days to add to this date. The program should then display the new date after adding the specified days.

Sample Input:

  • Date: 2023-01-01

  • Days to add: 30

Expected Output:2023-01-31

Solution:

from datetime import datetime, timedelta

# User input for the date and number of days to add
user_date = input("Enter a date (YYYY-MM-DD): ")
days_to_add = int(input("Enter the number of days to add: "))

# Convert the input date to a datetime object
date_object = datetime.strptime(user_date, "%Y-%m-%d")

# Add the days
new_date = date_object + timedelta(days=days_to_add)

# Format and print the new date
print("New date:", new_date.strftime("%Y-%m-%d"))

This example demonstrates converting a string to a datetime object, using timedelta to add days, and then formatting the output.

Problem 6: Difference Between Two Dates

Problem Description: Create a program that calculates the difference in days between two dates entered by the user. Both dates should be input in the format YYYY-MM-DD.

Sample Input:

  • First date: 2023-01-01

  • Second date: 2023-01-31

Expected Output:30 days

Solution:

from datetime import datetime

# User inputs for two dates
first_date_input = input("Enter the first date (YYYY-MM-DD): ")
second_date_input = input("Enter the second date (YYYY-MM-DD): ")

# Convert strings to datetime objects
first_date = datetime.strptime(first_date_input, "%Y-%m-%d")
second_date = datetime.strptime(second_date_input, "%Y-%m-%d")

# Calculate the difference
difference = abs((second_date - first_date).days)

print(f"The difference is: {difference} days")

This solution involves parsing two dates and computing the absolute difference in days between them, demonstrating basic date arithmetic and the use of abs() for ensuring a positive result.

Problem 7: Display the Month Name

Problem Description: Ask the user to enter a date in the format YYYY-MM-DD. The program should then display the name of the month for that date.

Sample Input:2023-03-15

Expected Output:March

Solution:

from datetime import datetime

# User inputs a date
date_input = input("Enter a date (YYYY-MM-DD): ")

# Convert the input to a datetime object
date_object = datetime.strptime(date_input, "%Y-%m-%d")

# Extract and print the month name
month_name = date_object.strftime("%B")
print(f"The month is: {month_name}")

This script shows how to use strftime("%B") to get the full month name from a date.

Problem 8: First Day of the Year

Problem Description: Write a program that asks the user to enter a year, then prints the date of the first Monday of that year.

Sample Input:2023

Expected Output:2023-01-02

Solution:

from datetime import datetime, timedelta

# User inputs a year
year = int(input("Enter a year: "))

# Find January 1st of the given year
jan_first = datetime(year, 1, 1)

# Calculate the first Monday
if jan_first.weekday() != 0:  # 0 is Monday
    jan_first += timedelta(days=(7-jan_first.weekday()))

# Print the date of the first Monday
print("The first Monday of the year is:", jan_first.strftime("%Y-%m-%d"))

This program calculates the weekday of January 1st and then finds the first Monday by adding the necessary number of days.

Problem 9: End of the Month Date

Problem Description: Write a Python program that asks the user to enter a year and a month (as numbers), then prints the last day of that month.

Sample Input:

  • Year: 2023

  • Month: 2

Expected Output:2023-02-28

Solution:

from datetime import datetime, timedelta

# User inputs for the year and month
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))

# Calculate the first day of the next month
if month == 12:
    next_month_first_day = datetime(year+1, 1, 1)
else:
    next_month_first_day = datetime(year, month+1, 1)

# Subtract one day to get the last day of the current month
last_day_of_month = next_month_first_day - timedelta(days=1)

# Print the result
print("The last day of the month is:", last_day_of_month.strftime("%Y-%m-%d"))

This solution demonstrates creating a datetime object for the first day of the next month and then subtracting one day to find the last day of the given month.

Problem 10: Number of Weekdays in a Month

Problem Description: Create a program that calculates the number of Mondays (or any specified weekday) in a given month and year entered by the user.

Sample Input:

  • Year: 2023

  • Month: 3

  • Weekday: Monday

Expected Output:4 Mondays in March 2023

Solution:

from datetime import datetime, timedelta

# User inputs
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
weekday_name = input("Enter the weekday (e.g., Monday): ")

# Find the first day of the month
first_day = datetime(year, month, 1)

# Find the first occurrence of the given weekday
day_num = first_day.weekday()  # Monday is 0, Sunday is 6
target_day_num = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].index(weekday_name)
days_until_target = (target_day_num - day_num) % 7
first_target_day = first_day + timedelta(days=days_until_target)

# Count the occurrences
count = 0
current_day = first_target_day
while current_day.month == month:
    count += 1
    current_day += timedelta(days=7)

# Print the result
print(f"{count} {weekday_name}s in {first_day.strftime('%B')} {year}")

This program calculates the number of specific weekdays in a given month by finding the first occurrence of that weekday and then counting how many times it occurs within the month.

Problem 11: Age in Days

Problem Description: Write a Python script that asks the user for their birthdate and calculates their age in days as of today.

Sample Input:2000-01-01

Expected Output:Approximately 8505 days old (Note: Output will vary based on the current date.)

Solution:

from datetime import datetime

# User inputs their birthdate
birthdate_input = input("Enter your birthdate (YYYY-MM-DD): ")
birthdate = datetime.strptime(birthdate_input, "%Y-%m-%d")

# Calculate age in days
today = datetime.now()
age_in_days = (today - birthdate).days

print(f"You are approximately {age_in_days} days old.")

This script shows how to calculate the difference in days between two dates, demonstrating the use of timedelta objects.

Problem 12: Adding Hours to Time

Problem Description: Create a program that asks the user for a time in the format HH:MM and a number of hours to add. The program should then print the new time.

Sample Input:

  • Time: 14:30

  • Hours to add: 5

Expected Output:19:30

Solution:

from datetime import datetime, timedelta

# User input for the time and hours to add
input_time = input("Enter a time (HH:MM): ")
hours_to_add = int(input("Enter the number of hours to add: "))

# Convert input to a datetime object
time_object = datetime.strptime(input_time, "%H:%M")

# Add the hours
new_time = time_object + timedelta(hours=hours_to_add)

# Print the new time
print("New time:", new_time.strftime("%H:%M"))

blog author image

sunil s

Quant Developer & Mentor

Back to Blog