Jessica Ferguson
Jessica Ferguson

Reputation: 109

Need Assistance with stripping the microsecond from epoch time

I have an API to which I have to send a epoch time start and end date. The only issue is that it will not accept microseconds.

I built a time function using datatime, however it calculates the microseconds. I tried the .replace(microsecond=0), but that just leaves the .0 on the Epoch, which my API complains about. I also tried exporting to strptime, but then my .timestamp function fails to parse it as a string.

timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()

params = {'start_date':timestart.timestamp(), 'end_date':timeend.timestamp()}

i would like to basically calculate current time in Epoch and time 24 hours ago (this does not have to be super precise) that I can pass to my API.

Upvotes: 1

Views: 45

Answers (3)

sentence
sentence

Reputation: 8933

An alternative solution to Pedro's one:

from datetime import datetime
from datetime import timedelta

timestart = (datetime.now() - timedelta(hours = 24)).strftime("%s")
timeend = datetime.now().strftime("%s")

params = {'start_date':timestart,
          'end_date':timeend}

Output:

{'start_date': '1554124346', 'end_date': '1554210746'}

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 99001

You can simply cast (Type Conversion) the values of timestart.timestamp() and timeend.timestamp(), which are floats, to ints, i.e.:

from datetime import datetime, timedelta
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()

s = int(timestart.timestamp()) 
e = int(timeend.timestamp())

params = {'start_date':s, 'end_date':e}
print(params)

Output:

{'start_date': 1554121647, 'end_date': 1554208047}

Demo

Upvotes: 4

fixatd
fixatd

Reputation: 1404

I usually use time.mktime() for converting datetimes to epoch time:

from datetime import datetime, timedelta
import time

timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()

params = {
  'start_date': int(time.mktime(timestart.timetuple())),
  'end_date': int(time.mktime(timeend.timetuple()))
}

# Output
{'start_date': 1554123099, 'end_date': 1554209499}

Upvotes: 0

Related Questions