Rounding DateTime objects
Floor
long ticks = date.Ticks / span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
Round (up on midpoint)
long ticks = (date.Ticks + (span.Ticks / 2) + 1)/ span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
Ceiling
long ticks = (date.Ticks + span.Ticks - 1)/ span.Ticks;
return new DateTime( ticks * span.Ticks, date.Kind );
How to round a datetime variable in Python?
In case you want to modify a datetime
object, you can round its .microsecond
attribute:
x = datetime.now()
print(x.isoformat(' '))
# 2022-05-04 15:36:01.055696
x = x.replace(microsecond=round(x.microsecond / 1000) * 1000)
print(x.isoformat(' '))
# 2022-05-04 15:36:01.056
In any case (even without modifying the object and rounding the microseconds), to get the representation you want you can format it with the appropriate method:
x.isoformat(' ', timespec='milliseconds')
# 2022-05-04 15:36:01.056
Note that modifying the object using round(x.microsecond / 1000) * 1000
for the microseconds will round them to the closest millisecond. If you just want to truncate the microseconds instead, use x.microsecond // 1000 * 1000
.
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
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'
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))
Related Topics
Why New Fb API 2.4 Returns Null Email on MVC 5 with Identity and Oauth 2
What's the Difference Between System.Type and System.Runtimetype in C#
How to Set Up a Web API Controller for Multipart/Form-Data
How Does MVC 4 List Model Binding Work
How to Access Winform Textbox Control from Another Class
How to Indefinitely Pause a Thread
Using Reflection in C# to Get Properties of a Nested Object
Using Image Control in Wpf to Display System.Drawing.Bitmap
How to Implement a Progress Bar Using the Mvvm Pattern
How to Post Using Httpclient Content Type = Application/X-Www-Form-Urlencoded
What Does the M Stand for in C# Decimal Literal Notation
How to Stream Webcam Video with C#
C++/Cli Wrapper for Native C++ to Use as Reference in C#
What Are the Definitions for Lparam and Wparam