To convert a timestamp to a date in Python, the easiest way is to use the datetime fromtimestamp() function to create a datetime object and then convert that to a date.
from datetime import datetime
ts = 1661540168
dt = datetime.fromtimestamp(ts).date()
print(dt)
#Output:
2022-08-26
When working with date and times, the ability to change between different variable types easily can be valuable.
One such case is if you want to convert a timestamp to a date.
To convert a timestamp to a date in Python, the easiest way is to use the datetime fromtimestamp() function to create a datetime object.
After you have the datetime object, then you can remove the time from the datetime and get the date with date().
Below is a simple example showing you how to convert a timestamp to a date in Python
from datetime import datetime
ts = 1661540168
dt = datetime.fromtimestamp(ts).date()
print(dt)
#Output:
2022-08-26
Convert Timestamp to Date with Timezone in Python
If the timestamp you are using needs to be converted to a date with a specific timezone, then you can specify a timezone with the optional tz argument for fromtimestamp().
Below is an example of converting a timestamp to a date object and specifying a timezone.
from datetime import datetime
import pytz
ts = 1661540168
dt = datetime.fromtimestamp(ts, tz=pytz.utc).date()
print(dt)
#Output:
2022-08-26
Hopefully this article has been useful for you to learn how to convert a timestamp into a date using Python.