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))
2
  • What does a print totimestamp(tm) show if you put right between the lines with tm = datetime.fromtimestamp ... and new_tm = tm.replace... ? Commented Feb 23, 2015 at 19:32
  • related: Converting datetime.date to UTC timestamp in Python Commented Feb 24, 2015 at 4:58

2 Answers 2

2

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

and now timestamp are identical.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.