In: Computer Science
Complete the code so that it can convert the date to day of week using python, the code should pass the doctest
def convert_datetime_to_dayofweek(datetime_string):
"""
This function takes date in the format MON DAY YEAR
HH:MM(PM/AM)
and returns the day of the week
Assume input string is UTC
>>> convert_datetime_to_dayofweek('Jun 1 2005
1:33PM')
'Wednesday'
>>> convert_datetime_to_dayofweek('Oct 25 2012
2:17AM')
'Thursday'
"""
# code goes here
Code -
import datetime
from datetime import date
def convert_datetime_to_dayofweek(date):
month, day, year, time = (i for i in date.split(' '))
months = dict(Jan =1 ,Feb = 2 , Mar =3 , Apr = 4 , May = 5 , Jun =
6,
Jul = 7 , Aug =8 , Sept=9 , Oct = 10 , Nov=11 , Dec=12)
day_of_week = datetime.date(int(year), int(months[month]),
int(day))
return day_of_week.strftime("%A")
if __name__=='__main__':
date = 'Oct 25 2012 2:17AM'
print(convert_datetime_to_dayofweek(date))
Explanation -
1. import datetime module .
datetime module is used to manipulate dates and time.
Also , import date class from datetime module.date class will manipulate the dates
2.define function convert_datetime_to_dayofweek which accepts single parameter date.
3.iterate through every item in date after splliting it at space. That is wherever space is present , date string will be split.Store it in month,day,year and time variable respectively.
Example -
date - Oct 25 2012 2:17AM
month, day, year, time = (i for i in date.split(' '))
Here month = oct , day=25,year=2012,time=2:17 AM
4.Since month is in name format we need to convert in into integer . define a dictionary months with key as month name and value as integer like Jan:1 , Feb :2 and so on
months = dict(Jan =1 ,Feb = 2 , Mar =3 , Apr = 4 , May = 5 , Jun
= 6,
Jul = 7 , Aug =8 , Sept=9 , Oct = 10 , Nov=11 , Dec=12)
5.Use datetime.date and pass year,month and day as arguments . Pass them as arguments after converting it into int.Hence use int(year), int(months[month]), int(day).
months[month] will give us the value of key month.
if month= Jun
then month[Jun] = 6
6.Use strftime("%A") to return the weekday from day_of_week.
7.Finally call the function convert_datetime_to_dayofweek in main and pass the date as argument to the function.