pandas to_datetime

pandas to_datetime

1. 将df中多列组合成一个datetime

import pandas as pd

df = pd.DataFrame({'year': [2015, 2016],
                   'month': [2, 3],
                   'day': [4, 5]})
print(df)
print(pd.to_datetime(df))

#
   year  month  day
0  2015      2    4
1  2016      3    5
0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]

2. 指定errors忽略 Out of bounds nanosecond timestamp , 或将报错datetime转为NaT

# df1 = pd.to_datetime('13000101', format='%Y%m%d')
# print(df1) # 报错 Out of bounds nanosecond timestamp 超过了
df2 = pd.to_datetime('13000101', format='%Y%m%d', errors='ignore')
print(df2) # 1300-01-01 00:00:00
df3 = pd.to_datetime('13000101', format='%Y%m%d', errors='coerce')
print(df3) # NaT

3. 将时间戳转datetime

df1 = pd.to_datetime(1490195805, unit='s')
print(df1) # 2017-03-22 15:16:45
df2 = pd.to_datetime(1490195805433502912, unit='ns')
print(df2) # 2017-03-22 15:16:45.433502912

4. 根据时间间隔列来转为datetime格式

df = pd.DataFrame([1,2,3])
print(df)
#
   0
0  1
1  2
2  3

# 需求: 将df的第一列作为时间间隔(天数),得到一列 今天+时间间隔 的日期
df1 = pd.to_datetime(df[0], unit='D',origin=time.strftime('%F',time.localtime()))
print(df1)
# 指定origin
print(df1)
# 
0   2021-04-13
1   2021-04-14
2   2021-04-15
Name: 0, dtype: datetime64[ns]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值