我怎么能同時顯示日期和時間在我'Time'的CSV檔案中列?我已經展示了我所看到的一些不同的例子?
df 'Time' 的樣子
“2021-11-01 08:00:00”
示例 1. 在控制臺中顯示正確但在 csv 檔案中不正確。
posix_time = pd.to_datetime(df['Time'], unit='ms')
df['Time'] = posix_time
df.to_csv (r'dataframe.csv', index = False, header=True)
0 2021-11-01 08:00:00
# In csv file ??? why not date and time like above only date ????
2021-11-01
示例 2. 在控制臺中顯示正確且僅在檔案日期中顯示正確。
posix_time = pd.to_datetime(df['Time'], unit='ms').dt.date
df['Time'] = posix_time
df.to_csv (r'dataframe.csv', index = False, header=True)
0 2021-11-01
# In csv file
2021-11-01
示例 3. 僅在控制臺和檔案中顯示正確。
posix_time = pd.to_datetime(df['Time'], unit='ms').dt.time
df['Time'] = posix_time
df.to_csv (r'dataframe.csv', index = False, header=True)
0 08:00:00
# In csv file
08:00:00
uj5u.com熱心網友回復:
您可以將str值轉換為datetime使用pd.to_datetime(). 有關如何設定format引數的更多資訊pd.to_datetime(),請參見https://www.dataindependent.com/pandas/pandas-to-datetime/
#file.csv
Time
2021-11-01 08:00:00
2021-11-02 09:00:00
2021-11-03 10:00:00
2021-11-04 11:00:00
2021-11-05 12:00:00
import pandas as pd
filepath = './file.csv' # to read your csv file
df = pd.read_csv(filepath)
print(df)
# For example, df will be printed look like:
# Time
#0 2021-11-01 08:00:00
#1 2021-11-02 09:00:00
#2 2021-11-03 10:00:00
#3 2021-11-04 11:00:00
#4 2021-11-05 12:00:00
df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%d %H:%M:%S') # to convert str to datetime format
df.to_csv('result.csv') # You can see that Time data is saved as "date time", not just date or time.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357915.html
