2

I know it is possible to convert nanoseconds in java to a timestamp like this:

import java.util.Date;
 public class DateDemo {

  public static void main(String args[]) {
  // Instantiate a Date object

    long i = 1462352019029395103L;
  // display time and date using toString()
   Date date = new Date(i / 1000000);

  System.out.println(date.toString());
  }
 }

This make: Wed May 04 08:53:39 UTC 2016

While in Python the output is:

>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(1462352019029395103 // 1000000000)
>>> s = dt.strftime('%Y-%m-%d %H:%M:%S')
>>> s
'2016-05-04 10:53:39'

The difference is 2 hours in python. I don't know exactly why. I read some earlier posts that Python couldn't convert nanoseconds. Is there any way I get the accurate timestamp in python?

Jongware
  • 22,200
  • 8
  • 54
  • 100
sockevalley
  • 351
  • 2
  • 4
  • 17

1 Answers1

8

Use utcfromtimestamp to make it equivalent with the datetime in Java:

>>> dt = datetime.utcfromtimestamp(1462352019029395103 // 1000000000)
>>> dt.strftime('%Y-%m-%d %H:%M:%S')
'2016-05-04 08:53:39'

Reference:

Coordinated Universal Time

'

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139