我正在使用 Python 中的 .sav (SPSS) 檔案。使用 PyreadStat(也使用 Pandas 時)匯入后,所有變數看起來都很好,但 datetime 變數除外。他們使用 Python 讀取為浮點型別的指數數。但它們的原始 SPSS 格式是日期型別的 dd-mmm-yy(例如 02-feb-2021)。
這就是日期變數的樣子
1.383160e 10
有沒有辦法使用 Python 將此格式轉換為日期時間?
我嘗試了各種使用 datetime 模塊和 time 模塊的方法。但我得到的是 2408 年的日期
# Here I'm using the float from the first row in the dataframe
time.gmtime(13831603200)
結果
time.struct_time(tm_year=2408, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=113, tm_isdst=0)
當我使用 datetime 模塊時:
python_date = datetime.fromtimestamp(13831603200).strftime('%d-%b-%Y, %H:%M:%S')
print(python_date)
2408 年 4 月 22 日,00:00:00
[使用 Python 時日期時間變數 (Vdatesub) 的顯示方式][1] [1]:https://i.stack.imgur.com/I7yza.png
uj5u.com熱心網友回復:
這在這兩篇文章(一篇 Python,一篇 R)下得到了回答:
將“自 1582 年 10 月 14 日以來的秒數”轉換為 Python 日期時間
將SPSS檔案讀入R,日期資料格式錯誤,生成更多變數
簡而言之:日期存盤為從 1582 年 10 月 14 日開始的秒數,而 Python 從 Epoch 日期(1970 年 1 月 1 日)開始。
您需要計算 1582-10-14 和 1970-01-01 之間的秒數,以根據這篇文章調整時間戳值:
平臺 localtime()/gmtime() 函式的時間戳超出范圍
(可能是 12,218,515,200 秒)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/507680.html