1

I need to convert a datetime object with microsecond resolution to a timestamp, the problem is that I don't get the same timestamp second's resolution.

For example the timestamp that I pass as an argument is 1424440192 and I get in return 1424429392.011750, why is this?, I Only changed microsecond value of the datetime object, so I expect to change only values after the dot. PD: In this example I'm only simulating one timestamp.

from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
    td = dt - epoch

    return td.total_seconds()
    #return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
    #10**6) / 1e6


timestamp_pc = 1424440192

tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)

print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))
Matthew0898
  • 263
  • 2
  • 13
progloverfan
  • 155
  • 2
  • 13
  • What does a `print totimestamp(tm)` show if you put right between the lines with `tm = datetime.fromtimestamp ...` and `new_tm = tm.replace...` ? – Savir Feb 23 '15 at 19:32
  • related: [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/q/8777753/4279) – jfs Feb 24 '15 at 04:58

2 Answers2

2

I get it. I changed tm = datetime.fromtimestamp(timestamp_pc) for tm = datetime.utcfromtimestamp(timestamp_pc)

and now timestamp are identical.

progloverfan
  • 155
  • 2
  • 13
0

From the fromtimestamp documentation:

If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.

Since your totimestamp function does not do the same timezone adjustment in reverse, the time is wrong by your time zone offset.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622