在Azure Databricks Notebook中获取EST当前时间的问题
Azure Databricks Notebook获取EST当前时间的解决方案
一、修正Spark代码的问题
你之前的Spark代码逻辑有误:当设置了spark.sql.session.timeZone为EST后,current_timestamp()已经会返回该时区的时间,再用from_utc_timestamp转换反而会导致时间偏移。另外,建议用US/Eastern代替EST,它会自动处理夏令时(EDT/EST切换)。
修正后的代码:
from pyspark.sql.functions import current_timestamp # 设置会话时区为美国东部(自动适配夏令时) spark.conf.set("spark.sql.session.timeZone", "US/Eastern") # 直接获取当前EST/EDT时间 current_est_df = spark.sql("SELECT current_timestamp() as current_est") current_est_df.show(truncate=False)
二、去除Python datetime的时区偏移
你看到的-04:00是因为生成的是带时区信息的datetime对象,打印时会显示时区偏移。要去掉它,有两种简单方法:
方法1:移除时区信息
from datetime import datetime from pytz import timezone est = timezone('US/Eastern') now_est = datetime.now(est).replace(tzinfo=None) print(now_est)
输出示例:2024-03-11 23:16:04.589275
方法2:格式化输出为字符串
from datetime import datetime from pytz import timezone est = timezone('US/Eastern') now_est = datetime.now(est) # 自定义格式,只保留日期时间部分 formatted_est = now_est.strftime("%Y-%m-%d %H:%M:%S.%f") print(formatted_est)
输出示例:2024-03-11 23:16:04.589275
三、其他获取EST时间并存入变量的方法
1. 从Spark DataFrame提取到Python变量
from pyspark.sql.functions import current_timestamp spark.conf.set("spark.sql.session.timeZone", "US/Eastern") # 获取时间并转为Python datetime对象 current_est = spark.sql("SELECT current_timestamp()").first()[0] # 转为字符串格式(可选) current_est_str = current_est.strftime("%Y-%m-%d %H:%M:%S.%f") print(current_est_str)
2. 使用Pandas处理时间
import pandas as pd # 获取当前EST时间 now_est = pd.Timestamp.now(tz='US/Eastern') # 移除时区信息 now_est_naive = now_est.tz_localize(None) print(now_est_naive)
3. 从UTC时间转换为EST
from datetime import datetime from pytz import timezone est = timezone('US/Eastern') # 先获取UTC时间,再转换为EST utc_now = datetime.utcnow() now_est = est.fromutc(utc_now) # 移除时区信息(可选) now_est_naive = now_est.replace(tzinfo=None) print(now_est_naive)
内容的提问来源于stack exchange,提问作者newbie
相关产品推荐
相关产品推荐

