w3resource

Pandas: Create a Series of Timestamps from a DataFrame of integer or string columns


13. Series of Timestamps from DataFrame

Write a Pandas program to create a series of Timestamps from a DataFrame of integer or string columns. Also create a series of Timestamps using specified columns.

Sample Solution:

Python Code :

import pandas as pd
df = pd.DataFrame({'year': [2018, 2019, 2020],
                   'month': [2, 3, 4],
                   'day': [4, 5, 6],
                   'hour': [2, 3, 4]})
print("Original dataframe:")
print(df)
result = pd.to_datetime(df)
print("\nSeries of Timestamps from the said dataframe:")
print(result)
print("\nSeries of Timestamps using specified columns:")
print(pd.to_datetime(df[['year', 'month', 'day']]))

Sample Output:

Original dataframe:
   year  month  day  hour
0  2018      2    4     2
1  2019      3    5     3
2  2020      4    6     4

Series of Timestamps from the said dataframe:
0   2018-02-04 02:00:00
1   2019-03-05 03:00:00
2   2020-04-06 04:00:00
dtype: datetime64[ns]

Series of Timestamps using specified columns:
0   2018-02-04
1   2019-03-05
2   2020-04-06
dtype: datetime64[ns]

For more Practice: Solve these Related Problems:

  • Write a Pandas program to create a series of Timestamps from a DataFrame containing separate year, month, and day columns.
  • Write a Pandas program to convert multiple date-related string columns into a unified Timestamp series and sort the result.
  • Write a Pandas program to extract and combine date components from a DataFrame into a Timestamp series and then validate the data type.
  • Write a Pandas program to create a Timestamp series using specified columns and then set it as the DataFrame index.

Go to:


Previous: Write a Pandas program to convert year and day of year into a single datetime column of a dataframe.
Next: Write a Pandas program to check if a day is a business day (weekday) or not.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.