【python】pandas 时间序列转换

1. 时间戳-->时间

time_stamp = 1677895200000  # 2023-03-04 10:00:00
pd.to_datetime(time_stamp, unit='ms')  # Timestamp('2023-03-04 02:00:00')  utc时间
pd.to_datetime(time_stamp, unit='ms', origin='1970-01-01 08:00:00')  # Timestamp('2023-03-04 10:00:00')
pd.to_datetime(time_stamp, unit='ms', origin='1970-01-01 08:00:00').strftime('%F %T')  # '2023-03-04 10:00:00'

time_str = '2023-03-04 10:00:00'
pd.to_datetime(time_str, format='%Y-%m-%d %H:%M:%S')  # Timestamp('2023-03-04 10:00:00')
pd.to_datetime(time_str, format='%Y-%m-%d %H:%M:%S').strftime('%F')  # '2023-03-04'
pd.to_datetime(time_str, format='%Y-%m-%d %H:%M:%S').strftime('%F %T')  # ''2023-03-04 10:00:00'

2. 时间格式化

df['time']  # dtype: datetime64
df['time'][0]  # pandas._libs.tslibs.timestamps.Timestamp
df['time'].dt.strftime('%F %T')  # '2023-03-04 10:00:00'

3. 字符串-->时间

df['time']  # dtype: object
df['time'][0]  # str
pd.to_datetime(df['time'][0], format='%Y-%m-%d %H:%M:%S"')  # Timestamp('2023-03-03 08:02:17')
pd.to_datetime(df['time'], format='%Y-%m-%d %H:%M:%S')

4. 时间-->时间戳

df = pd.DataFrame({'date': ['2011-04-24 01:30:00.000']})
df['date'] = pd.to_datetime(df['date'])
df['date'].astype('int64')//1e9
# 0    1.303609e+09
# Name: date, dtype: float64
(df['date'].astype('int64')//1e9).astype('int')
# 0    1303608600
# Name: date, dtype: int32
posted @ 2023-03-10 14:59  是阿杰呀  阅读(253)  评论(0)    收藏  举报