Question: 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

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.

"""

 

 

 

from dateutil import parser

import datetime

import pytz


 

try:

   timestamp = parser.parse(timestamp)


 

except:

    result = parser.parse(timestamp)

    if result.tzinfo is None and tzsource is None:

        return result

    elif result.tzinfo is None and type(tzsource) == str:

        time1 = pytz.timezone(tzsource)

        e = time1.localize(result)

        return e

   elif result.tzinfo is not None and tzsource is None:

      return result

   elif result.tzinfo is None and tzsource is not None:

        g = result.replace(tzinfo=tzsource.tzinfo)

        return g

   elif result.tzinfo is not None and tzsource is not None:

        h = result.replace()

       return h

   else:

      try:

          timestamp = datetime.fromtimestamp(timestamp)

          return timestamp

    except ValueError:

          return None


I am trying to solve this function, but keep getting an error message:

 

The call str_to_time('2016-04-15', None) returns None, not datetime.datetime(2016, 4, 15, 0, 0)

 

I've included the code I'm using below

 

 

def str_to_time(timestamp,tzsource=None):

"""

Returns the datetime object for the given timestamp (or None if timestamp is invalid).

 


Step by Step Solution

3.40 Rating (150 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

It looks like there are a few issues in your code Let me help you correct them from da... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!