Reference Guide - Datetime Manipulation
Reference Guide - Datetime Manipulation
The following tables can serve as reference guides to remind you of the shorthand code for
manipulating datetime strings into individual objects.
Below, you will find a table with the datetime functions you can use to help you manipulate
datetime objects in different ways.
%A Weekday Sunday
%H 24 hours 00 to 23
%I 12 hours 01 to 12
%m Month 01 to 12
%M Minute 00 to 59
%p AM or PM AM/PM
%S Seconds 00 to 61
%w Weekday 0 to 6
%Y Year 2022
%z Offset +0900
You’ve learned that the datetime module in Python’s standard library contains a number of
classes used to work with time data, including date, time, datetime, timedelta,
timezone, and tzinfo. Remember, modules are similar to libraries, in that they are groups of
related classes and functions, but they are generally subcomponents of libraries. Classes are
data types that bundle data and functionality together.
NumPy and pandas have their own datetime classes that offer significant performance boosts
when working with large datasets. Pandas datetime classes, like the rest of the pandas library,
are built on NumPy. These classes have very similar (and in many cases identical) functionality
to Python’s native datetime classes, but they run more efficiently due to NumPy and pandas’
vectorization capabilities. Therefore, although you can use datetime data in pandas, it’s
generally better to use NumPy or pandas datetime objects when working in pandas, if possible.
NumPy’s datetime classes include, most notably, datetime64 and timedelta64. Like
datetime objects, datetime64 objects contain date and time information in a single data
structure; and, like timedelta objects, timedelta64 objects contain information pertaining
to spans of time.
This series contains string data, but it can be converted to datetime64 data using the
pd.to_datetime() function:
my_series = pd.to_datetime(my_series)
my_series
Refer to the pandas to_datetime() documentation for more information about this function.
When a Series object contains datetime data, you can use dt to access various properties of
the data. For example:
print(my_series.dt.year)
print()
print(my_series.dt.month)
print()
print(my_series.dt.day)
Note that it’s not uncommon to import the datetime module from Python’s standard library as
dt. You may have encountered this yourself. In such case, dt is being used as an alias. The
pandas dt Series accessor (as demonstrated in the last example) is a different thing entirely.
Refer to the pandas dt accessor documentation for more information.
Key takeaways
Use reference guides like the tables above throughout your career to help remind you of the
different ways to manipulate datetime objects. Even experts in the field use reference guides,
rather than memorizing all this information. Getting familiar with guides like these will be
beneficial because you will be using them throughout your career as a data professional.
Citations:
# Title Link