Nitin Kothari
Nitin Kothari

Reputation: 97

Subtract days from timestamp python

I am calculating end timestamp and then I have to subtract days (example days = 10) from the timestamp and then convert it to get the start timestamp. Calculating start_timestamp and end_timestamp like this:

import datetime

end_timestamp = time.time()
end_time = datetime.datetime.fromtimestamp(end_timestamp)

start_date = end_time.date() - datetime.timedelta(days=10)
start_timestamp = datetime.datetime.strptime(str(start_date) + " " + str(end_time.time()), '%Y-%m-%d %H:%M:%S.%f').timestamp())

I need both the start and end in timestamp format only. What is the best pythonic way to do this?

Upvotes: 1

Views: 4069

Answers (1)

FObersteiner
FObersteiner

Reputation: 25634

what about something like

from datetime import datetime, timedelta, timezone

t1 = datetime.now(timezone.utc) # end time
t0 = t1 - timedelta(10)         # start time

# if you need UNIX time:
start_ts, end_ts = t0.timestamp(), t1.timestamp()
print(start_ts, end_ts)
# 1608972059.652785 1609836059.652785

# if needed you can combine date and time from different datetime objects:
dt = datetime.combine(t0.date(), t1.time()).replace(tzinfo=timezone.utc)
print(dt.isoformat())
# 2020-12-26T08:40:59.652785+00:00

I'm explicitly setting the time zone to UTC to avoid any hickups due to Python treating naive datetime as local time while UNIX time refers to a UTC date/time1.

If you work with UNIX time in seconds since the epoch, you could also add/subtract days directly as multiples of the seconds in a day (86400):

import time

t1 = time.time()
t0 = t1 - 86400*10

dt = datetime.fromtimestamp(t0, tz=timezone.utc)
print(dt.isoformat())
# 2020-12-26T08:51:07.015367+00:00

1 However, note that UNIX time does not include leap seconds.

Upvotes: 2

Related Questions