'Convert string tz to add to localized datetime object
I am new and learning. I believe my function is written well to handle the given specification. My problem comes when trying to convert a given string tz to add to my datetime object as localized. Any help is greatly appreciated!
The specific error I am getting: The call str_to_time('2016-05-12T16:23', 'America/Chicago') returns None, not datetime.datetime(2016, 5, 12, 16, 23, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>).
My full code:
import datetime
from dateutil.parser import parse, parser
import pytz
def str_to_time(timestamp,tz=None):
"""
Returns the datetime object for the given timestamp (or None if stamp 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 timezone, then it should keep that timezone even if
the value for tz is not None. Otherwise, if timestamp has no timezone and
tz if not None, this this function will assign that timezone to the datetime
object.
The value for tz can either be a string or a time OFFSET. If it is a string,
it will be the name of a timezone, and it should localize the timestamp. If
it is an offset, that offset should be assigned to the datetime object.
Parameter timestamp: The time stamp to convert
Precondition: timestamp is a string
Parameter tz: The timezone to use (OPTIONAL)
Precondition: tz is either None, a string naming a valid time zone,
or a time zone OFFSET.
"""
# HINT: Use the code from the previous exercise and update the timezone
# Use localize if timezone is a string; otherwise replace the timezone if not None
# parse the given timestamp
# return None if not a valid date / parse crash
try:
a = parse(timestamp)
# check to see if timestamp has a timezone. keep the timezone
if a.tzinfo != None:
result = a
# if timestamp is valid and has no tz and tz is also = None, return the timestamp
if a.tzinfo == None and tz == None:
result = a
# if timestamp has no timezone and there is a value for tz, assign the given tz
# if tz is a string, localize the tz to the timestamp.
# if tz is an offset, assign to the datetimeobject
if a.tzinfo == None:
if tz != None:
if type(tz) == str:
tz = pytz.timezone(tz)
result = tz.localized(a)
else:
result = a.replace(tzinfo = tz)
except:
result = None
return result
Solution 1:[1]
I answered my own question. I had gotten mixed up on some of my variable naming. Here is the corrected portion of code:
if type(tz) == str:
time1 = pytz.timezone(tz)
result = time1.localize(a)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | KV1 |