问题描述
限时送ChatGPT账号..我正在尝试将代码从 Python 转换为 Java.我需要用 Java 重写 timeDelta
函数.这是 Python 中的代码:
def timeDate(date):返回(时间增量(秒=日期 * 3600 % 86400))
有没有人知道如何制作一个功能相同的功能?
解决方案 double hours = 21.37865107050986;long nanos = Math.round(hours * TimeUnit.HOURS.toNanos(1));持续时间 d = Duration.ofNanos(nanos);//删除任何一整天d = d.minusDays(d.toDays());System.out.println(d);
打印:
<块引用>PT21H22M43.143853836S
这意味着:持续时间为 21 小时 22 分 43.143853836 秒.
假设:我知道您想要一个持续时间(您链接的文档说一个 timedelta
对象代表一个持续时间").我已经将 date
视为一个浮点数小时,你的模运算让我相信你想要模 1 天的持续时间(所以 26 小时应该作为 2 小时的持续时间出现).
Java 中的 Duration
类用于持续时间,因此您应该使用它.它不接受用于创建的浮点数,因此我将您的小时数转换为纳秒并四舍五入为整数.对于转换,我乘以 1 小时内的纳秒数,这是我从调用 TimeUnit
中得到的(与我们自己相乘相比,这给出了更清晰且不易出错的代码).
上面的代码会默认给出大量小时数的错误结果,因此您应该在使用之前检查范围.最多 250 万小时(10 万天或近 300 年)您应该是安全的.
请注意:如果 date
是一天中的时间而不是持续时间,则情况完全不同.在这种情况下,您应该在 Java 中使用 LocalTime
.正好是一天中的某个时间(没有日期和时区).
nanos = nanos % TimeUnit.DAYS.toNanos(1);LocalTime timeOfDay = LocalTime.ofNanoOfDay(nanos);System.out.println(timeOfDay);
<块引用>
21:22:43.143853836
链接: Duration
类的文档
I am trying to convert code from Python to Java. I need to rewrite the timeDelta
function in Java. Here is the code in Python:
def timeDate(date):
return (timedelta(seconds=date * 3600 % 86400))
Does anyone have any idea on how to make a function that acts the same?
解决方案 double hours = 21.37865107050986;
long nanos = Math.round(hours * TimeUnit.HOURS.toNanos(1));
Duration d = Duration.ofNanos(nanos);
// Delete any whole days
d = d.minusDays(d.toDays());
System.out.println(d);
This prints:
PT21H22M43.143853836S
Which means: a duration of 21 hours 22 minutes 43.143853836 seconds.
Assumptions: I understand that you want a duration (the docs you link to say "A timedelta
object represents a duration"). I have taken date
to be a floating-point number of hours, and your modulo operation lead me to believe that you want the duration modulo 1 day (so 26 hours should come out as a duration of 2 hours).
The Duration
class in Java is for durations, hence is the one that you should use. It doesn’t accept a floating point number for creation, so I converted your hours so nanoseconds and rounded to whole number. For the conversion I multiplied by the number of nanoseconds in 1 hour, which I got from the call to TimeUnit
(this gives clearer and less error-prone code than multiplying out ourselves).
The code above will tacitly give incorrect results for numerically large numbers of hours, so you should check the range before using it. Up to 2 500 000 hours (100 000 days or nearly 300 years) you should be safe.
Please note: if date
was a time of day and not a duration, it’s a completely different story. In this case you should use LocalTime
in Java. It’s exactly for a time of day (without date and without time zone).
nanos = nanos % TimeUnit.DAYS.toNanos(1);
LocalTime timeOfDay = LocalTime.ofNanoOfDay(nanos);
System.out.println(timeOfDay);
21:22:43.143853836
Link: Documentation of the Duration
class
这篇关于TimeDelta java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论