📅  最后修改于: 2023-12-03 15:19:21.705000             🧑  作者: Mango
dt.strftime
Pandas is a popular data analysis and manipulation library in Python. dt
is a datetime-enabled class available in the Pandas Series object. dt.strftime
is a method that formats datetime objects as a string.
The syntax of the dt.strftime
method is:
Series.dt.strftime(format, *args, **kwargs)
format
(mandatory): The format string, written using strftime syntax.*args
: Variable length argument list. These are positional arguments that may be supplied to the format string.**kwargs
: Keyword arguments that are passed to the format function.Let's create a Pandas Series of Datetime objects and see how to format them using the dt.strftime
method.
import pandas as pd
data = pd.Series([
'2022-06-18 03:30 PM',
'2022-06-19 02:45 AM',
'2022-06-20 06:00 PM',
])
data = pd.to_datetime(data)
# format dates as dd-mm-yyyy
data.dt.strftime("%d-%m-%Y")
# format dates as Month day, year hour:minute AM/PM
data.dt.strftime("%B %d, %Y %I:%M %p")
The above code will output following:
0 18-06-2022
1 19-06-2022
2 20-06-2022
dtype: object
0 June 18, 2022 03:30 PM
1 June 19, 2022 02:45 AM
2 June 20, 2022 06:00 PM
dtype: object
Here are some of the common format codes used in dt.strftime
method.
| Code | Description |
| ---- | ----------- |
| %Y
| Year (4 digits) |
| %y
| Year (2 digits) |
| %m
| Month (e.g. 01) |
| %d
| Day of the Month (01-31) |
| %B
| Full month name (e.g. June) |
| %b
| Abbreviated month name (e.g. Jun) |
| %A
| Full weekday name (e.g. Saturday) |
| %a
| Abbreviated weekday name (e.g. Sat) |
| %I
| Hour in 12-hour format (01-12)|
| %H
| Hour in 24-hour format (00-23)|
| %M
| Minute (00-59) |
| %S
| Second (00-59) |
| %p
| AM/PM |
You can find a complete list of strftime format codes on strftime.org.
In summary, the dt.strftime
method allows for easy formatting of datetime objects in a Pandas Series object using strptime syntax. It is a powerful tool for data analysts to understand and format datetime data.