About Lesson
Pandas supports the use of datetime
objects for representing date and time. You can create datetime
objects directly or by converting strings into datetime
format using pd.to_datetime()
.
a. Creating a Timestamp from a String
You can convert a string representation of a date into a Timestamp
object.
date_str = '2024-11-30'
timestamp = pd.to_datetime(date_str)
print(f"Timestamp: {timestamp}")
Output:
Timestamp: 2024-11-30 00:00:00
Here, pd.to_datetime()
converts the date string into a Pandas Timestamp
object. The time is set to midnight by default.
b. Creating Timestamps with Specific Time
You can also create a timestamp with specific time values:
date_str = '2024-11-30 14:30:00'
timestamp_with_time = pd.to_datetime(date_str)
print(f"Timestamp with Time: {timestamp_with_time}")
Output:
Timestamp with Time: 2024-11-30 14:30:00
c. Creating DateTimeIndex
For handling a series of time-based data, you can create a DatetimeIndex
. This is useful when you need to index data by dates.
date_range = pd.date_range('2024-11-01', periods=5, freq='D')
print("DatetimeIndex:")
print(date_range)
Output:
DatetimeIndex(['2024-11-01', '2024-11-02', '2024-11-03', '2024-11-04', '2024-11-05'],
dtype='datetime64[ns]', freq='D')
Here, pd.date_range()
generates a DatetimeIndex
of 5 days starting from ‘2024-11-01’.