python - 在 Pyspark 中将字符串转换为时间戳对象
问题描述
我正在尝试将字符串转换为 Pyspark 中的时间戳格式。
from pyspark.sql.types import DateType
df = spark.createDataFrame([('28/Mar/2021:06:29:54 -0700',)], ['dt'])
df.select(date_format('dt', 'd/M/y:h:m:s Z').alias('date')).collect()
这似乎不起作用,可能是因为 date_format 函数无法将其识别为有效格式。我明白了:
[行(日期=无)]
无论如何,我可以让 pyspark 函数理解格式,类似于 Python 中的 datetime 模块吗?
from datetime import datetime
datetime.strptime('28/Mar/2021:06:29:54 -0700', '%d/%b/%Y:%H:%M:%S %z')
当我们传递格式时,它会创建一个有效的日期时间对象
datetime.datetime(2021, 3, 28, 6, 29, 54, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200)))
解决方案
与 Python 日期时间模块不同,在 Spark 中,您需要为每个模式指定字符数。此外,用于to_timestamp
将字符串转换为时间戳类型。date_format
反之亦然,即将时间戳类型转换为字符串。
from pyspark.sql.functions import to_timestamp
df = spark.createDataFrame([('28/Mar/2021:06:29:54 -0700',)], ['dt'])
df.select(to_timestamp('dt', 'dd/MMM/yyyy:HH:mm:ss Z').alias('date')).collect()
# gives [Row(date=datetime.datetime(2021, 3, 28, 14, 29, 54))]
推荐阅读
- python - 使用字典值作为 df 的变量
- npm - 如何使用 npm 定位 git #branch@version?
- php - 如何在此处添加按日期排序?
- r - 通过匹配字符串分隔列
- oracle - 有没有更快的方法在 oracle pl/sql 中每周对 120k 条记录执行合并?
- nginx - 如何修复此 NGINX 502 Bad Gateway 错误?
- push-notification - Firebase Cloud Messaging - 识别特定推送通知消息的传递状态
- html - 如何强制横幅在 CSS 中放大并全宽?
- spring-boot - 当我们在 restfull web 服务中有多层服务调用方法时如何使用 junit 和 mockito
- arduino - 用arduino自动发送短信?