Python Get the Date N Days Ago
Calculate the date N days ago and convert it to a specified format.
Example 1
import
time
import
datetime
First obtain the date in time-array format
threeDayAgo
=
(
datetime
.
datetime
.
now
(
)
datetime
.
timedelta
(
days
=
3
)
)
Convert to a timestamp
timeStamp
=
int
(
time
.
mktime
(
threeDayAgo
.
timetuple
(
)
)
)
Convert to another string format
otherStyleTime
=
threeDayAgo
.
strftime
(
"
%Y-%m-%d %H:%M:%S
"
)
(
otherStyleTime
)
The output of the code above is:
2019-05-18 18:06:08
Example 2
import
time
import
datetime
# Given timestamp
timeStamp
=
1557502800
dateArray
=
datetime
.
datetime
.
utcfromtimestamp
(
timeStamp
)
threeDayAgo
=
dateArray
datetime
.
timedelta
(
days
=
3
)
(
threeDayAgo
)
The output of the code above is:
2019-05-07 15:40:00
Python3 Examples