Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Get the Date N Days Ago

Python Get the Date N Days Ago

Document Object Reference Manual Python3 Examples

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

"

)

print

(

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

)

print

(

threeDayAgo

)

The output of the code above is:


2019-05-07 15:40:00

Document Object Reference Manual Python3 Examples