代码之家  ›  专栏  ›  技术社区  ›  LaSul

使用来自时间戳和国家/地区的pyspark进行时区转换

  •  0
  • LaSul  · 技术社区  · 7 年前

    我正在尝试用pyspark将UTC日期转换为本地时区(使用国家/地区)的日期。 我把国家作为字符串,日期作为时间戳

    所以输入是:

    date = Timestamp('2016-11-18 01:45:55') # type is pandas._libs.tslibs.timestamps.Timestamp

    country = "FR" # Type is string

    import pytz
    import pandas as pd
    
    def convert_date_spark(date, country):
        timezone = pytz.country_timezones(country)[0]
    
        local_time = date.replace(tzinfo = pytz.utc).astimezone(timezone)
        date, time = local_time.date(), local_time.time()
    
        return pd.Timestamp.combine(date, time)
    
    # Then i'm creating an UDF to give it to spark
    
    convert_date_udf = udf(lambda x, y : convert_date_spark(x, y), TimestampType())
    

    然后我把它用于给Spark供电的功能:

    data = data.withColumn("date", convert_date_udf(data["date"], data["country"]))
    

    我有以下错误:

    类型错误:TZINFO参数必须是NONE或TZINFO子类,而不是类型“str”

    预期输出是具有相同格式的日期

    正如用python测试的那样,convert-date-spark函数可以工作,但这在pyspark中不起作用。

    enter image description here

    你能帮我找到解决办法吗?

    谢谢

    1 回复  |  直到 7 年前
        1
  •  1
  •   DuÅ¡an Maďar    7 年前

    使用 tzinfo 实例而不是 string 作为时区。

    >>> timezone_name = pytz.country_timezones(country)[0]
    >>> timezone_name
    'Europe/Paris'
    >>> timezone = pytz.timezone(timezone_name)
    >>> timezone
    <DstTzInfo 'Europe/Paris' LMT+0:09:00 STD>
    >>> 
    
    推荐文章