Pandas DatetimeThe Pandas can provide the features to work with time-series data for all domains. It also consolidates a large number of features from other Python libraries like scikits.timeseries by using the NumPy datetime64 and timedelta64 dtypes. It provides new functionalities for manipulating the time series data. The manipulations performed in Pandas Datetime can be listed as:
The time series tools are most useful for data science applications and deals with other packages used in Python. Example 1: DatetimeIndexThe below code generates a sequence of eight dates starting from '5/4/2013' with a frequency of one second. Code Output: DatetimeIndex(['2013-05-04 00:00:00', '2013-05-04 00:00:01', '2013-05-04 00:00:02', '2013-05-04 00:00:03', '2013-05-04 00:00:04', '2013-05-04 00:00:05', '2013-05-04 00:00:06', '2013-05-04 00:00:07'], dtype='datetime64[ns]', freq='S') Example 2: ConversionThe below code converts a DataFrame with separate columns for year, month, and day into a single datetime format using the pd.to_datetime() function in Pandas. Code Output: 0 2014-05-20 1 2012-07-17 dtype: datetime64[ns] Example 3: Range GenerationThis below code generates a sequence of five dates starting from '2017-06-04' with a frequency of one second. Code Example3:Output: DatetimeIndex(['2017-06-04 00:00:00', '2017-06-04 00:00:01', '2017-06-04 00:00:02', '2017-06-04 00:00:03', '2017-06-04 00:00:04'], dtype='datetime64[ns]', freq='S') Example 4: LocalizationThe below python datetime code localizes the timezone of a datetime sequence represented by the variable 'dmy' to UTC using the tz_localize() function in Pandas. Code Output: DatetimeIndex(['2017-06-04 00:00:00+00:00', '2017-06-04 00:00:01+00:00', '2017-06-04 00:00:02+00:00', '2017-06-04 00:00:03+00:00', '2017-06-04 00:00:04+00:00'], dtype='datetime64[ns, UTC]', freq='S') Example 5: Time Series OperationsThe below code is written to perform time series operations like rolling mean. Code Output: DataFrame: Value 2022-01-01 10 2022-01-02 15 2022-01-03 8 2022-01-04 12 2022-01-05 9 Rolling Mean: 2022-01-01 NaN 2022-01-02 NaN 2022-01-03 11.000000 2022-01-04 11.666667 2022-01-05 9.666667 Freq: D, Name: Value, dtype: float64 Conclusion:The Pandas library gives strong usefulness to working with datetime information in Python. It offers different elements to deal with, control, and break down dates and times productively. Next TopicPandas Time Offset |