There are times when you might need to work with timestamps in Python. For example, you might want to analyze a dataset containing timestamps to understand the frequency or distribution of events.
However, sometimes the timestamp data includes more information than necessary, like the time down to the millisecond, and it would be much more useful to simplify this to just the date.
In this tutorial, we’ll learn how to extract only the date from a timestamp in Python using the datetime module.
Step 1: Understanding the problem
When you have a timestamp (for instance, from a database record), it usually includes the date and time up to the millisecond or even microsecond. But in many cases, we don’t need the exact time and instead, we need just the date.
That’s when we need to extract the date from the timestamp. For instance, if we have a timestamp like 2021-10-11 10:15:30.936728, and we only need the date which is 2021-10-11.
Step 2: Importing necessary libraries
To extract date from a timestamp, Python offers a built-in module called datetime. Let’s import it:
1 |
import datetime |
Step 3: Convert timestamp to datetime object
The first step in extracting the date from a timestamp is to convert the timestamp to a datetime object. Here’s how to do that:
1 2 |
timestamp = "2021-10-11 10:15:30.936728" datetime_obj = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f') |
In the above code, we are using the strptime function of the datetime module. The strptime function is used to convert a string of time to a datetime object. The ‘%Y-%m-%d %H:%M:%S.%f’ is the format of the string time, where:
- %Y : Year
- %m : Month
- %d : Day
- %H : Hour
- %M : Minute
- %S : Second
- .%f : Microsecond
Step 4: Extract the date from the datetime object
Once the timestamp is converted to a datetime object, you can then extract the date like so:
1 |
date = datetime_obj.date() |
Now, the variable date holds the date extracted from the timestamp.
Complete Code
Here is the complete code that extracts the date from the timestamp:
1 2 3 4 5 6 7 |
import datetime timestamp = "2021-10-11 10:15:30.936728" datetime_obj = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f') date = datetime_obj.date() print(date) |
Output:
1 |
2021-10-11 |
Conclusion
Extracting date from timestamps is a common operation in many data analysis tasks. We’ve seen how to solve this problem in a few steps using Python’s built-in module datetime.
As usual, understanding the problem and the tools at hand is key to finding efficient and effective solutions.