专业的编程技术博客社区

网站首页 > 博客文章 正文

定义一个时间戳转化函数:解决德国站时间戳问题

baijin 2024-12-02 16:43:01 博客文章 5 ℃ 0 评论

亚马逊销售数据中,不同站点因为时间的文字表现形式是不一样的,我们在做汇总分析的时候,需要将日期改成通用统一的格式,需要对特定国家的日期格式进行清洗,以下函数用于解决德国站时间戳问题:


        # 时间戳转化函数:解决德国站时间戳问题
        def convert_date(date_string, input_formats, output_format):
            for date_format in input_formats:
                try:
                    datetime_object = datetime.datetime.strptime(date_string, date_format)
                    return datetime_object.strftime(output_format)
                except ValueError:
                    pass
            # 如果多种日期格式都没法正常处理,返回'原值'
            return date_string
				# 定义输入日期格式
        input_formats = ["%B %d, %Y %I:%M:%S %p %Z",
                        "%d %b %Y %H:%M:%S GMT%z",
                        "%d.%m.%Y %H:%M:%S %Z",
                        "%d %b %Y %I:%M:%S %p GMT%z",
                        "%d %b %Y %H:%M:%S %Z",
                        "%d %B %Y %H:%M:%S %Z",
                        "%d %b. %Y %H:%M:%S %Z",
                        ]
        # 定义输出日期格式
        output_format = "%Y-%m-%d %H:%M:%S"
        # 设置时区字典
        tzinfos = {'PDT':-7*60*60, 'GMT+9':9*60*60}
        # 处理德国站日期字符串
        if df['日期'].str.contains('.').any():
            df['日期'] = df['日期'].apply(lambda x: convert_date(x, input_formats, output_format))

        # 转化时间字符串输出日期格式
        df['日期'] = df['日期'].apply(lambda x: parser.parse(x,tzinfos=tzinfos).strftime(output_format)) 

#亚马逊跨境电商[话题]#?#python自动化#?#pandas#?

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表