I would like to convert my timestamp
column from a datetime to UNIX.
import time
import datetime
import pandas as pd
file = 'input.csv'
colnames=['number', 'timestamp']
df = pd.read_csv(file, header=0)
print(df.head())
number timestamp
0 0 2019-01-03 08:55:05
1 1 2019-01-06 03:24:25
2 2 2019-01-09 04:25:44
3 3 2019-01-10 06:52:53
4 4 2019-01-19 03:26:28
Python script that works for a single value:
time.mktime(datetime.datetime.strptime( TIMESTAMPVALUE , "%Y-%m-%d %H:%M:%S").timetuple())
I would like to do this in one step for the whole column without having to iterate over each value.
In order to convert a column to datetime, you can use parse_dates
parameter of read_csv
In [9]: df = pd.read_csv("a.csv", parse_dates=["timestamp"])
In [10]: df
Out[10]:
timestamp
0 2019-01-03 08:55:05
1 2019-01-06 03:24:25
2 2019-01-09 04:25:44
3 2019-01-10 06:52:53
4 2019-01-19 03:26:28
In [11]: (df["timestamp"] - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')
Out[11]:
0 1546505705
1 1546745065
2 1547007944
3 1547103173
4 1547868388
Name: timestamp, dtype: int64
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.