Home »
Python »
Python Programs
Pandas: Convert from datetime to integer timestamp
Given a pandas dataframe, we have to convert from datetime to integer timestamp.
By Pranit Sharma Last updated : October 03, 2023
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Problem statement
Suppose we are given a DataFrame with some integer in the date format, we know how to convert these values in datetime format (using pandas.to_datetime() method), but here, we need to convert the datetime type value to integer timestamp value.
Converting from datetime to integer timestamp
For this purpose, we will typecast to int using astype(int64) and divide it by 10**9 to get a number of seconds to the unix epoch start.
The timestamp value is the value that contains the date and time values in a particular format. It comes from the Datetime library. If we use pandas.Timestamp() method and pass a string inside it, it will convert this string into time format, but here will convert to integer timestamp.
Let us understand with the help of an example,
Python program to convert from datetime to integer timestamp
# Importing pandas package
import pandas as pd
# Import numpy
import numpy as np
# Creating a dictionary
d = {'time': [pd.to_datetime('2019-01-15 13:25:43')]}
# Creating DataFrame
df = pd.DataFrame(d)
# Display original DataFrame
print('Original DataFrame:\n',df,'\n')
# Creating integer timestamp
new_time = pd.to_datetime(df['time']).astype('int64')/ 10**9
# Display New time
print("Integer timestamp :\n",new_time,"\n")
Output
The output of the above program is:
Python Pandas Programs »