0

So I have a datetime.datetime object and I want to compute the next minute of it. What I mean by next minute is the same time but at the very beginning of the next minute. For example, the next minute of 16:38:23.997 is 16:39:00.000.

I can do that easily by adding 1 to the minute and setting every smaller values to 0 (seconds, milliseconds, etc), but I'm not satisfied with this way, because I may need to carry out by checking if the minute becomes higher than 60, and if the hour is bigger than 24... and it ends up being over complicated for what I want to do

Is there a "simple" pythonic way to achieve this ?

Mateo Vial
  • 658
  • 4
  • 13
  • 2
    Did you look at the datetime documentation? You add a timedelta – roganjosh Feb 07 '23 at 16:06
  • 1
    Are you calculating this in UTC or do you have to take into account possible daylight time savings? Sometimes the next minute after 02:59:38 might be 04:00:00 (local time). – Niko Föhr Feb 07 '23 at 16:06
  • 1
    See: [python time + timedelta equivalent](https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent) – Niko Föhr Feb 07 '23 at 16:11
  • 1
    Using `timedelta` and then truncating the smaller units as suggested by roganjosh would work. Another way would be to convert the datetime to a unix timestamp (float value in seconds) and something like `next_t = t - (t % 60) + 60` and then convert `next_t` back to a datetime (taking care to do a timezone-aware conversion both times). – Anentropic Feb 07 '23 at 16:14
  • If you are already at the top of the minute, do you want to keep that minute or get the next minute? – chepner Feb 07 '23 at 16:16
  • Yes, but that is the same issue as what I describe : I'd need to precisely get a timedelta that is equal to the difference between now and the following minute – Mateo Vial Feb 07 '23 at 16:49

1 Answers1

2

You can use the replace method of the datetime object to set the seconds and microseconds to zero, and then add a timedelta of one minute to get the next minute.

from datetime import datetime, timedelta

# example datetime object
dt = datetime(2023, 8, 5, 16, 38, 23, 997)
print(f'Original datetime: {dt}')

# set seconds and microseconds to zero
dt = dt.replace(second=0, microsecond=0)
print(f'Seconds and microseconds set to zero: {dt}')

# add one minute
next_minute = dt + timedelta(minutes=1)
print(f'Next minute: {next_minute}')
PartMent
  • 21
  • 1