Considering a pandas dataframe in python having a column named time
of type integer, I can convert it to a datetime
format with the following instruction.
df['time'] = pandas.to_datetime(df['time'], unit='s')
so now the column has entries like: 2019-01-15 13:25:43
.
What is the command to revert the string to an integer timestamp value (representing the number of seconds elapsed from 1970-01-01 00:00:00
)?
I checked pandas.Timestamp
but could not find a conversion utility and I was not able to use pandas.to_timedelta
for this.
Is there any utility for this conversion?
strftime() object. In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function. Returns : It returns the string representation of the date or time object.
You can use the following basic syntax to convert a timestamp to a datetime in a pandas DataFrame: timestamp. to_pydatetime () The following examples show how to use this function in practice. Example 1: Convert a Single Timestamp to a Datetime. The following code shows how to convert a single timestamp to a datetime:
Timestamp is the pandas equivalent of python’s Datetime and is interchangeable with it in most cases. It’s the type used for the entries that make up a DatetimeIndex, and other timeseries oriented data structures in pandas. Value to be converted to Timestamp. Offset which Timestamp will have. Time zone for time which Timestamp will have.
Python datetime to integer timestamp. 1 Python3. from datetime import datetime. curr_dt = datetime.now () print("Current datetime: ", curr_dt) timestamp = int(round(curr_dt.timestamp ())) ... 2 Python3. 3 Python3. 4 Python3.
First, we get the current time using datetime.datetime.now (). And then import the pytz library to instantiate the timezone object to localize the datetime. Convert the datetime object into timestamp using datetime.timestamp () method. We will get the timestamp in seconds. Round off and convert the timestamp in integer to get the integer timestamp.
You can typecast to int using astype(int)
and divide it by 10**9
to get the number of seconds to the unix epoch start.
import pandas as pd df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]}) df_unix_sec = pd.to_datetime(df['time']).astype(int)/ 10**9 print(df_unix_sec)
The easiest way is to use .value
pd.to_datetime('1970-01-01').value
If you want to apply it to the whole column, just use .apply
:
df['time'] = df['time'].apply(lambda x: x.value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With