How To Extract Date From Timestamp Python

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.

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.

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.

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.

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.

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.