Azure Databricks Notebook中的当前时间戳(EST)

3 投票
1 回答
72 浏览
提问于 2025-04-14 16:43

我需要获取当前的东部标准时间(EST),但是用 current_timestamp() 得到的是太平洋标准时间(PST)。

我试过以下代码,但它不管用,显示的时间比东部时间少了6个小时:

# Import the current_timestamp function
from pyspark.sql.functions import from_utc_timestamp
    
# Set the timezone to EST
spark.conf.set("spark.sql.session.timeZone", "EST")
    
# Get the current timestamp in EST
current_timestamp_est = spark.sql("SELECT from_utc_timestamp(current_timestamp(), 'EST') as current_timestamp_est")
    
# Show the current timestamp in EST
current_timestamp_est.show(truncate = False)

我还试过下面的代码。但是显示的时间是 2024-03-11 23:16:04.589275-04:00。为什么会有 -4:00 这个部分?有没有办法去掉 -4:00

from datetime import datetime
from pytz import timezone

est = timezone('US/Eastern')
now_est = datetime.now(est)
#now_est1 = now_est[:26]
print(now_est)

有没有其他方法可以把当前的时间戳存到一个变量里,并且是东部标准时间的?

1 个回答

0

要去掉 -04:00,你可以在第二种方法中使用 .strftime() 这个功能:

from datetime import datetime
from pytz import timezone

est = timezone('US/Eastern')
now_est = datetime.now(est).strftime('%Y-%m-%d %H:%M:%S')
print(now_est)

Output:
2024-04-04 09:42:58

至于第一种方法,不要直接设置 EST 作为时区,最好是指定一个全球范围内的地点,比如 America/New_York,这样就可以去掉偏移值 -04:00,具体做法如下:

spark.conf.set("spark.sql.session.timeZone", "America/New_York")
current_timestamp_est = spark.sql("SELECT current_timestamp() as current_timestamp_est")

current_timestamp_est.show(truncate=False)

Output:
+--------------------------+
|current_timestamp_est     |
+--------------------------+
|2024-04-04 09:42:12.082136|
+--------------------------+

撰写回答