How to convert nanosecond uptime to a readable datetime format
I extracted accelerometer data from an Android wearable. While looking at the data, I realized that timestamps are not unix overridable. After researching, I found that the timestamp is actually nanoseconds of uptime. My problem is related to Accelerometer SensorEvent timestamp Same. But since I don’t know Java, I don’t know how to convert it using the solutions provided. Is there any Python method to convert nanoseconds in uptime to a readable datetime format? An example of a timestamp is “45900482044637”.
Solution
tl; dr
Duration.ofNanos ( 45_900_482_044_637L )
PT12H45M0.482044637S
java.time
Java 8 and later have a Duration
for this class, as new part of java.time frameworks (see Tutorial )。 These new classes have nanosecond resolution (nine decimal places). Duration
represents the span of time in hours, minutes, and seconds.
Android does not currently use Java 8 technology, but has a back-port of java.time to Java 6 & 7. Further adaptation to Android in the ThreeTenABP project.
Note that L
is appended to long's
numeric literal. In addition, underlining makes lengthy numbers easier for humans to decipher.
long input = 45_900_482_044_637L;
Let’s convert that number to a Duration
object.
Duration duration = Duration.ofNanos ( input );
When we generate the string representation of the Duration
object, we get a string standard formatted with ISO 8601. The standard uses the PnYnMnDTnHnMnS
pattern, where P
marks the beginning and T
separates the year-month-day from the hour-minute-second.
System.out.println ( "duration: " + duration );
The answer is twelve hours, forty-five minutes and one second.
duration: PT12H45M0.482044637S
About java.time
within the java.time framework in Java 8 and later. These classes replace the troublesome old classes legacy datetime classes, eg java.util.Date
, Calendar
, & SimpleDateFormat
.
<a href=”http://www.joda.org/joda-time/” rel=”noreferrer noopener nofollow”>Joda-Time project, now in Maintenance mode, it is recommended to migrate to the java.time class .
To learn more, see >Oracle Tutorial Search for many examples and explanations. The specification is JSR 310
Where do I get the java.time class?
- Java SE 8 , Java SE 9, then
- Built.
- Part of a standard Java API with a bundle implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Many java.time features are backported to Java 6 and 7 in ThreeTen-Backport
- Android
- Later versions of Android bundle implement the java.time class.
- For the early Androids, ThreeTenABP project adaptation ThreeTen-Backport (as described above). See also How to use ThreeTenABP….
ThreeTen-Extra project extends java.time with additional classes. The project is a testing ground for future things that might be added to java.time. You may find some useful classes here, such as Interval
, YearWeek
, YearQuarter
, and more .