python how to round a timestamp by minute?
You can use datetime.datetime.replace(microsecond=0)
Example:
import datetime
from dateutil import tz
now = datetime.datetime.now()
print(now.replace(tzinfo=tz.gettz('UTC')).astimezone(tz.gettz('America/New_York')))
# > 2021-02-03 04:47:55.259843-05:00
print(now.replace(tzinfo=tz.gettz('UTC')).astimezone(tz.gettz('America/New_York')).replace(microsecond=0))
# > 2021-02-03 04:47:55-05:00
How to round datetime previous 10 minute with python
The easiest way is to construct a new datetime
with the desired values.
def timeround10(dt):
return datetime.datetime(dt.year, dt.month, dt.day, dt.hour, (dt.minute // 10) * 10))
Round time to nearest hour python
I experimented a bit with jpp but ended up with a different solution as adding one hour at hour 23 crashed the thing.
from datetime import datetime, timedelta
now = datetime.now()
def hour_rounder(t):
# Rounds to nearest hour by adding a timedelta hour if minute >= 30
return (t.replace(second=0, microsecond=0, minute=0, hour=t.hour)
+timedelta(hours=t.minute//30))
print(now)
print(hour_rounder(now))
Returns:
2018-02-22 23:42:43.352133
2018-02-23 00:00:00
Rounding time off to the nearest second - Python
Using for loop
and str.split()
:
dts = ['2017-06-25 00:31:53.993',
'2017-06-25 00:32:31.224',
'2017-06-25 00:33:11.223',
'2017-06-25 00:33:53.876',
'2017-06-25 00:34:31.219',
'2017-06-25 00:35:12.634']
for item in dts:
date = item.split()[0]
h, m, s = [item.split()[1].split(':')[0],
item.split()[1].split(':')[1],
str(round(float(item.split()[1].split(':')[-1])))]
print(date + ' ' + h + ':' + m + ':' + s)
2017-06-25 00:31:54
2017-06-25 00:32:31
2017-06-25 00:33:11
2017-06-25 00:33:54
2017-06-25 00:34:31
2017-06-25 00:35:13
>>>
You could turn that into a function:
def round_seconds(dts):
result = []
for item in dts:
date = item.split()[0]
h, m, s = [item.split()[1].split(':')[0],
item.split()[1].split(':')[1],
str(round(float(item.split()[1].split(':')[-1])))]
result.append(date + ' ' + h + ':' + m + ':' + s)
return result
Testing the function:
dts = ['2017-06-25 00:31:53.993',
'2017-06-25 00:32:31.224',
'2017-06-25 00:33:11.223',
'2017-06-25 00:33:53.876',
'2017-06-25 00:34:31.219',
'2017-06-25 00:35:12.634']
from pprint import pprint
pprint(round_seconds(dts))
['2017-06-25 00:31:54',
'2017-06-25 00:32:31',
'2017-06-25 00:33:11',
'2017-06-25 00:33:54',
'2017-06-25 00:34:31',
'2017-06-25 00:35:13']
>>>
Since you seem to be using Python 2.7, to drop any trailing zeros, you may need to change:
str(round(float(item.split()[1].split(':')[-1])))
to
str(round(float(item.split()[1].split(':')[-1]))).rstrip('0').rstrip('.')
I've just tried the function with Python 2.7 at repl.it and it ran as expected.
How to round down minute on datetime every 10 minutes
This seems like a non-answer answer, but I don't know how you could improve upon what you already have. It works, it's concise, it's flexible (not hard-coded to a specific interval), it truncates fractions of a minute, and it maintains the Kind
property. What more do you need?
Test code:
static void Main(string[] args)
{
TestRoundingForHourAfter(DateTime.Parse("10 AM"));
TestRoundingForHourAfter(DateTime.Parse("10 AM").AddTicks(123456789));
}
static void TestRoundingForHourAfter(DateTime baseTime)
{
foreach (DateTime input in Enumerable.Range(0, 60).Select(minutes => baseTime + TimeSpan.FromMinutes(minutes)))
{
DateTime output = RoundDown(input, TimeSpan.FromMinutes(10));
Console.WriteLine($"{input:hh:mm:ss.fffffff} rounds to {output:hh:mm:ss.fffffff}");
}
}
public static DateTime RoundDown(DateTime dt, TimeSpan d)
{
var delta = dt.Ticks % d.Ticks;
return new DateTime(dt.Ticks - delta, dt.Kind);
}
Test output:
10:00:00.0000000 rounds to 10:00:00.0000000
10:01:00.0000000 rounds to 10:00:00.0000000
10:02:00.0000000 rounds to 10:00:00.0000000
10:03:00.0000000 rounds to 10:00:00.0000000
10:04:00.0000000 rounds to 10:00:00.0000000
10:05:00.0000000 rounds to 10:00:00.0000000
10:06:00.0000000 rounds to 10:00:00.0000000
10:07:00.0000000 rounds to 10:00:00.0000000
10:08:00.0000000 rounds to 10:00:00.0000000
10:09:00.0000000 rounds to 10:00:00.0000000
10:10:00.0000000 rounds to 10:10:00.0000000
...
10:00:12.3456789 rounds to 10:00:00.0000000
10:01:12.3456789 rounds to 10:00:00.0000000
10:02:12.3456789 rounds to 10:00:00.0000000
10:03:12.3456789 rounds to 10:00:00.0000000
10:04:12.3456789 rounds to 10:00:00.0000000
10:05:12.3456789 rounds to 10:00:00.0000000
10:06:12.3456789 rounds to 10:00:00.0000000
10:07:12.3456789 rounds to 10:00:00.0000000
10:08:12.3456789 rounds to 10:00:00.0000000
10:09:12.3456789 rounds to 10:00:00.0000000
10:10:12.3456789 rounds to 10:10:00.0000000
...
How to round a datetime up to a specific time?
If the result is a timezone-aware datetime object in a timezone with a non-fixed UTC offset then you can't just call .replace()
or .combine()
-- it may create a datetime with a wrong UTC offset. The issue is similar to How do I get the UTC time of "midnight" for a given timezone? (00:00
is used instead of 08:00
).
Assuming 8AM always exists and unambiguous in PST:
from datetime import datetime, time as datetime_time, timedelta
import pytz # $ pip install pytz
def next_8am_in_pst(aware_dt, tz=pytz.timezone('America/Los_Angeles')):
pst_aware_dt = tz.normalize(aware_dt.astimezone(tz)) # convert to PST
naive_dt = round_up_to_8am(pst_aware_dt.replace(tzinfo=None))
return tz.localize(naive_dt, is_dst=None)
def round_up_to_8am(dt):
rounded = datetime.combine(dt, datetime_time(8))
return rounded + timedelta(rounded < dt)
Example:
>>> str(next_8am_in_pst(datetime.now(pytz.utc)))
'2016-02-25 08:00:00-08:00'
Related Topics
Syntaxerror: Multiple Statements Found While Compiling a Single Statement
Python Numpy Arange Unexpected Results
Generate a Random Derangement of a List
Why Not Generate the Secret Key Every Time Flask Starts
Play an Animated Gif in Python with Tkinter
How Can One Continuously Generate and Track Several Random Objects with a Time Delay in Pygame
How to Check If Directory Exists in Python
What Is :: (Double Colon) in Python When Subscripting Sequences
Why Is Tensorflow 2 Much Slower Than Tensorflow 1
Setting an Environment Variable in Virtualenv
How to Dynamically Load a Python Class
Count Consecutive Occurences of Values Varying in Length in a Numpy Array
Pyqt4 Wait in Thread for User Input from Gui
When Are Objects Garbage Collected in Python
Python - Pygame Error When Executing Exe File
How to Get the "Id" After Insert into MySQL Database with Python