Question
Having trouble completing this problem: Implement str_to_time Read the specification of the function str_to_time in the module funcs. Implement this function according to its specification.
Having trouble completing this problem:
Implement str_to_time
Read the specification of the function str_to_time in the module funcs. Implement this function according to its specification. This function is very similar to one that you have implemented in the previous exercise. The difference is that there is now an optional argument to specify a time zone.
Read the specification very carefully. In some cases, the datetime object you parse from the timestamp string parameter may already have a time zone. If so, the tzsource parameter should be ignored. Also, the time zone tools you need depend on the type of the tzsource parameter. If the tzsource parameter is another datetime object, you will need to extract the tzinfo from that object. Otherwise, you will need to use the pytz module to create a time zone and call the localize method. These steps are all shown in the course video, and you should review the video if you are unsure of the steps.
When you have implemented the function, test your answer with the test script before moving on to the next function.
"""
Functions for parsing time values and determining daylight hours.
"""
def str_to_time(timestamp,tzsource=None):
"""
Returns the datetime object for the given timestamp (or None if timestamp is invalid).
This function should just use the parse function in dateutil.parser to convert the timestamp to a datetime object.
If it is not a valid date (so the parser crashes), this function should return None. If the timestamp has a time zone, then it should keep that time zone even if the value for tzsource is not None. Otherwise, if timestamp has no time zone and tzsource is not None, then this function will use tzsource to assign a time zone to the new datetime object.
The value for tzsource can be None, a string, or a datetime object. If it is a string, it will be the name of a time zone, and it should localize the timestamp. If it is another datetime, then the datetime object created from timestamp should get the same time zone as tzsource.
Parameter timestamp: The time stamp to convert
Precondition: timestamp is a string
Parameter tzsource: The time zone to use (OPTIONAL)
Precondition: tzsource is either None, a string naming a valid time zone, or a datetime object.
"""
# HINT: Use the code from the previous exercise and add time zone handling.
# Use localize if tzsource is a string; otherwise replace the time zone if not None
pass # Implement this function
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started