pd.to_datetime是Pandas库中的函数,可以将字符串转换为Timestamp格式,并且可以转换多种格式的时间字符串。
pd.to_datetime(arg, format=None, errors='raise', dayfirst=False, yearfirst=False, utc=None, box=True, exact=True, unit=None, infer_datetime_format=False, origin='unix')
# unit作用
import pandas as pd
timestamp = 1626345600 # 时间戳表示2021-07-15 00:00:00(秒为单位)
date = pd.to_datetime(timestamp, unit='s')
print(date)
输出结果:
2021-07-15 00:00:00
# to_datetime用法
dates = pd.to_datetime(['2021/12/01', '2021/12/02', '2021/12/03'])
print(dates)
输出结果:DatetimeIndex(['2021-12-01', '2021-12-02', '2021-12-03'], dtype='datetime64[ns]', freq=None)
from datetime import datetime
import pandas as pd
now = pd.Timestamp(datetime.now())
print(now)
输出结果:
2023-07-15 21:12:52.952046
import pandas as pd
date1 = pd.Timestamp('2022-12-01 12:30:00')
date2 = pd.Timestamp('2023-5-03 07:08:14')
print(date2 - date1)
输出结果:
152 days 18:38:14