代码之家  ›  专栏  ›  技术社区  ›  Auto-learner

如何使用Python检查unicode字符串中是否存在时区

  •  0
  • Auto-learner  · 技术社区  · 7 年前

    我在JSON数据中有时间戳字段,其中一些时间戳具有这种格式的时间戳 str("2014-05-12 00:00:00") 还有一个是这种格式的 str("2015-01-20 08:28:16 UTC") . 我只想从字符串中获取年、月、日字段。我试过以下方法,但不确定问题出在哪里。有人能纠正我吗。我已经从StackOverflow那里找到了一些答案,但没有任何帮助。

    from datetime import datetime
    date_posted=str("2014-05-12 00:00:00")
    date_posted_zone=str("2015-01-20 08:28:16 UTC")
    
    def convert_timestamp(date_timestamp=None):
        if '%Z' in date_timestamp:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
        else:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
        return d.strftime("%Y-%m-%d")
    
    print convert_timestamp(date_posted_zone)
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Prabhanshu tiwari    7 年前

    我试着用下面的代码来搜索str中的时区及其工作状态。

    from datetime import datetime
    date_posted=str("2014-05-12 00:00:00")
    date_posted_zone=str("2015-01-20 08:28:16 UTC")
    zone=date_posted_zone.split(" ")
    print(zone[2])
    def convert_timestamp(date_timestamp=None):
        if zone[2] in date_timestamp:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
        else:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
        return d.strftime("%Y-%m-%d")
    
    print convert_timestamp(date_posted_zone)
    
        2
  •  1
  •   chepner    7 年前

    %Z 在时间戳值中;只有 strptime strftime )实际上可以使用格式字符。

    def convert_timestamp(date_timestamp=None):
        try:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
        except ValueError:
            d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
        return d.strftime("%Y-%m-%d")
    

    def convert_timestamp(date_timestamp):
        return date_timestamp.split()[0]
    
        3
  •  0
  •   hoi ja    5 年前
    from dateutil import parser
    
    datetime_no_timezone = parser.parse("2015-01-20 08:28:16")
    datetime_with_timezone = parser.parse("2015-01-20 08:28:16+02:00")
    
    if datetime_no_timezone.tz == None:
        # CODE ALWAYS GO THROUGH THIS
        pass
    
    if datetime_no_timezone.tz:
        # CODE ALWAYS GO THROUGH THIS
        pass