首页 > 解决方案 > 转换字符串 tz 以添加到本地化的日期时间对象

问题描述

我是新手,正在学习。我相信我的函数写得很好,可以处理给定的规范。当尝试将给定的字符串 tz 转换为本地化的日期时间对象时,我的问题就出现了。任何帮助是极大的赞赏!

我得到的具体错误: 调用 str_to_time('2016-05-12T16:23', 'America/Chicago') 返回 None,not datetime.datetime(2016, 5, 12, 16, 23, tzinfo=<DstTzInfo '美国/芝加哥的 CDT-1 日,19:00:00 DST>)。

我的完整代码:

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

标签: python

解决方案


我回答了我自己的问题。我对我的一些变量命名搞混了。这是代码的更正部分:

       if type(tz) == str:
            time1 = pytz.timezone(tz)
            result = time1.localize(a)

推荐阅读