简体   繁体   English

如何更改日期时间分辨率

[英]How to change datetime resolution

Is there a simple way to state that有没有一种简单的方法来 state

a = '2020-01-01 19:30:33.996628' 
b = '2020-01-01 19:30:34' 

a and b are equal. ab相等。 If the time resolution of a is changed to second, then a could be equal to b .如果a的时间分辨率更改为秒,则a可能等于b How to implement it with code?如何用代码实现它?

Set to next second设置为下一秒

  • Add the timedelta difference between 1e6 and a.microsecond添加1e6a.microsecond之间的timedelta差异
from datetime import timedelta, datetime

a = datetime.fromisoformat('2020-01-01 19:30:33.996628')

a = a + timedelta(microseconds=(1e6 - a.microsecond))

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 34)

print(a.strftime('%Y-%m-%d %H:%M:%S'))

>>> 2020-01-01 19:30:34

Set to current second设置为当前秒

  • With .replace(microsecond=0)使用.replace(microsecond=0)
from datetime import datetime

a = datetime.fromisoformat('2020-01-01 19:30:33.996628')

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 33, 996628)

a = a.replace(microsecond=0)

print(a)

>>> datetime.datetime(2020, 1, 1, 19, 30, 33)

if you treat both of them as datetime objects, you can use arithmetic operators on them.如果将它们都视为datetime时间对象,则可以对它们使用算术运算符。 For example, you can subtract them and check if the result satisfy a condition (like less then one minute different) as you wise例如,您可以明智地减去它们并检查结果是否满足条件(例如相差不到一分钟)

An easier way to use rounding for comparison:-使用舍入进行比较的更简单方法:-

import datetime
from dateutil import parser

a = '2020-01-01 19:30:33.996628' 
b = '2020-01-01 19:30:34' 

a = parser.parse(a)
b = parser.parse(b)

a == b
False

format_str = '%Y-%m-%d %H:%M'

a_rounded = datetime.datetime.strptime(datetime.datetime.strftime(a, format_str), format_str)
b_rounded = datetime.datetime.strptime(datetime.datetime.strftime(b, format_str), format_str)

a_rounded == b_rounded
True

To this you can add flexibility according to your need like I have rounded up to comparison in Minutes .为此,您可以根据需要增加灵活性,就像我在Minutes中进行的比较一样。 So in your case the format_str would be like this:-因此,在您的情况下, format_str 将是这样的:-

format_str = '%Y-%m-%d %H:%M:%S'

The function datetime_round_s() below rounds to the closest second (like usual rounding of numbers):下面的 function datetime_round_s()舍入到最接近的秒数(就像通常的数字舍入一样):

import datetime

def datetime_round_s(date_time: datetime.datetime) -> datetime.datetime:
    return (date_time + datetime.timedelta(microseconds=5e5)).replace(microsecond=0)

a = datetime.datetime.fromisoformat('2020-01-01 19:30:33.996628')
b = datetime.datetime.fromisoformat('2020-01-01 19:30:34')

print(a)
print(datetime_round_s(a))
print(datetime_round_s(a) == b)

otuput:输出:

2020-01-01 19:30:33.996628
2020-01-01 19:30:34
True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM