Convert data from a string to a timestamp
if we have a list of string data that resembles DateTime, we can first convert it to a dataframe using pd.DataFrame() method and convert it to DateTime column using pd.to_datetime() method.
Python3
# importing pandas import pandas as pd # creating string data string_data = [ '2020-01-31' , '2020-02-29' , '2020-03-31' , '2020-04-30' , '2020-05-31' , '2020-06-30' , '2020-07-31' , '2020-08-31' , '2020-09-30' , '2020-10-31' , '2020-11-30' , '2020-12-31' , '2021-01-31' , '2021-02-28' , '2021-03-31' , '2021-04-30' ] Data = pd.DataFrame(string_data, columns = [ 'Date' ]) Data[ 'Date' ] = pd.to_datetime(Data[ 'Date' ]) print (Data.info()) |
Output:
<class 'pandas.core.frame.DataFrame'> RangeIndex: 16 entries, 0 to 15 Data columns (total 1 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Date 16 non-null datetime64[ns] dtypes: datetime64[ns](1) memory usage: 256.0 bytes None
According to the format of our string values, we can convert them to DateTime. datetime.strptime() function can be used in this scenario
Python3
# importing pandas import pandas as pd from datetime import datetime # string data string_data = [ 'May-20-2021' , 'May-21-2021' , 'May-22-2021' ] timestamp_data = [datetime.strptime(x, '%B-%d-%Y' ) for x in string_data] print (timestamp_data) Data = pd.DataFrame(timestamp_data, columns = [ 'Date' ]) print (Data.info()) |
Output:
[datetime.datetime(2021, 5, 20, 0, 0), datetime.datetime(2021, 5, 21, 0, 0), datetime.datetime(2021, 5, 22, 0, 0)]
<class ‘pandas.core.frame.DataFrame’>
RangeIndex: 3 entries, 0 to 2
Data columns (total 1 columns):
# Column Non-Null Count Dtype
— —— ————– —–
0 Date 3 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 152.0 bytes
Manipulating Time Series Data in Python
A collection of observations (activity) for a single subject (entity) at various time intervals is known as time-series data. In the case of metrics, time series are equally spaced and in the case of events, time series are unequally spaced. We may add the date and time for each record in this Pandas module, as well as fetch dataframe records and discover data inside a specific date and time range.
Contact Us