Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
2 solutions solution in Clear category for Date and Time Converter by donnythelegend
# Import datetime module for solution 2.
import datetime as dt
def date_time(time: str) -> str:
## Solution 1: Without datetime module.
## Split time into date and time_ using whitespace.
#date, time_ = time.split()
## Split date into day, month, year using period.
#day, month, year = date.split('.')
## Split time_ into hour and minute using colon.
#hour, minute = time_.split(':')
## Define suffix strings.
#hour_str = 'hour' if int(hour)==1 else 'hours'
#minute_str = 'minute' if int(minute)==1 else 'minutes'
## Define list of month strings.
#months = ['January', 'February', 'March', 'April', 'May', 'June',
# 'July', 'August', 'September', 'October', 'November', 'December']
## Return concatenated string in final format.
#return f'{str(int(day))} {months[int(month) - 1]} {year} year {str(int(hour))} {hour_str} {str(int(minute))} {minute_str}'
# Solution 2: Using datetime module.
# Parse time into datetime object.
date_time_ = dt.datetime.strptime(time, '%d.%m.%Y %H:%M')
# Define suffix strings.
hour_str = "hour" if date_time_.hour == 1 else "hours"
minute_str = "minute" if date_time_.minute == 1 else "minutes"
# Return concatenated string in final format.
return date_time_.strftime(f'{date_time_.day} %B %Y year {date_time_.hour} {hour_str} {date_time_.minute} {minute_str}')
if __name__ == '__main__':
print("Example:")
print(date_time('01.01.2000 00:00'))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"
assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"
assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"
print("Coding complete? Click 'Check' to earn cool rewards!")
April 20, 2021