How do I round down an epoch timestamp to the nearest minute in Python?
Question:
I’d like to round down/floor an epoch/Unix timestamp so as to remove the seconds.
I’m using Python 2.x and Python 3.x
E.g.
1488728901 = Sun, 05 Mar 2017 15:48:21 GMT
to:
1488728880 = Sun, 05 Mar 2017 15:48:00 GMT
There’s some great answers by using datetime
to manipulate the time but it seems OTT if my input and output are integers.
Answers:
A simple bit of maths:
int(timestamp//60 * 60)
(//
replicates Python 2.x division (/
) where the result is a whole number)
Or if you’re not clever you could use arrow:
>>> import arrow
>>> timestamp = arrow.get(1488728901)
>>> timestamp
<Arrow [2017-03-05T15:48:21+00:00]>
>>> timestamp = timestamp.floor('minute')
>>> timestamp.format('YYYY-MMM-DD HH:mm:ss')
'2017-Mar-05 15:48:00'
you can do one thing here lets suppose col has your unix value. modified_value=((col+30*1000)/60*1000).cast("long")
— it will be decimal or integer covert it into proper integer if
modified_value_final = modified_value*60*1000
Example val=1488728901
modifeid_value=(1488728901+30000)/60000 = 24,812.64835
modified_value = 24,812 --after casting to long
final_modified_value = 24812*60000=1,488,720,000
I’d like to round down/floor an epoch/Unix timestamp so as to remove the seconds.
I’m using Python 2.x and Python 3.x
E.g.
1488728901 = Sun, 05 Mar 2017 15:48:21 GMT
to:
1488728880 = Sun, 05 Mar 2017 15:48:00 GMT
There’s some great answers by using datetime
to manipulate the time but it seems OTT if my input and output are integers.
A simple bit of maths:
int(timestamp//60 * 60)
(//
replicates Python 2.x division (/
) where the result is a whole number)
Or if you’re not clever you could use arrow:
>>> import arrow
>>> timestamp = arrow.get(1488728901)
>>> timestamp
<Arrow [2017-03-05T15:48:21+00:00]>
>>> timestamp = timestamp.floor('minute')
>>> timestamp.format('YYYY-MMM-DD HH:mm:ss')
'2017-Mar-05 15:48:00'
you can do one thing here lets suppose col has your unix value. modified_value=((col+30*1000)/60*1000).cast("long")
— it will be decimal or integer covert it into proper integer if
modified_value_final = modified_value*60*1000
Example val=1488728901
modifeid_value=(1488728901+30000)/60000 = 24,812.64835
modified_value = 24,812 --after casting to long
final_modified_value = 24812*60000=1,488,720,000