In this tutorial, we will learn how to extract the date from a timestamp in Python. Timestamps are widely used to store date and time information in computer systems.
Python’s built-in datetimelibrary provides a convenient way to work with timestamps and extract specific date and time components. Anyone performing date-time manipulations and calculations in Python will find this tutorial helpful.
Step 1: Import the datetime module
First, we need to import the datetime module, which provides functionalities to work with date and time in Python.
1 |
import datetime |
Step 2: Create a timestamp
If you already have a timestamp, you can skip this step. In case you don’t have a timestamp and want to create one, you can use the datetime.datetime.now() function to get the current timestamp.
1 2 3 4 |
# Get the current timestamp current_timestamp = datetime.datetime.now() print("Current Timestamp:", current_timestamp) |
The output will look like:
Current Timestamp: 2021-09-29 14:30:48.987264
Step 3: Extract the date part from the timestamp
Now we have the timestamp, and we will extract the date part from it using the date() function.
1 2 |
date_extracted = current_timestamp.date() print("Extracted Date: ", date_extracted) |
The output will be:
Extracted Date: 2021-09-29
This gives us the date portion from the timestamp object.
Step 4: Extract date components (optional)
Sometimes we may need individual components of the date like day, month, and year. To achieve this, we can use the day, month, and year attributes of the date object.
1 2 3 4 5 6 7 |
day = date_extracted.day month = date_extracted.month year = date_extracted.year print("Day: ", day) print("Month: ", month) print("Year: ", year) |
The output will be:
Day: 29 Month: 9 Year: 2021
Using these attributes, we can further process or manipulate the date.
Full Code
Here’s the complete code for extracting a date from a timestamp in Python.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import datetime # Get the current timestamp current_timestamp = datetime.datetime.now() print("Current Timestamp:", current_timestamp) # Extract the date part from the timestamp date_extracted = current_timestamp.date() print("Extracted Date: ", date_extracted) # Extract date components day = date_extracted.day month = date_extracted.month year = date_extracted.year print("Day: ", day) print("Month: ", month) print("Year: ", year) |
Conclusion
In this tutorial, we learned how to extract the date from a timestamp in Python using the datetime module. We went through creating a timestamp, extracting the date part from it, and further extracting individual date components (day, month, and year) if required. This will be helpful when working with date and time data in Python.