Reputation: 2001
I'd like to convert an epoch time stamp (eg, et =1351036517.179364) to a datetime.datetime object. So far, I've used time.ctime(et) which gives me a string of something like "Fri Oct 5 22:20:33 2012 ".
Eventually, I need the datetime object to compute time difference between two datapoints, the other datapoint is a datetime object as well.
Thanks!
Upvotes: 1
Views: 11618
Reputation: 5518
use fromtimestamp
as referenced in the documentation
Return the local date corresponding to the POSIX timestamp [...and if tz is supplied...] the timestamp is converted to [supplied] tz’s time zone.
Here is an example of such a timestamp as generated by python(updated thanks to @jfs and Paul Ganssle)
from datetime import datetime, timezone
epoch = datetime.now(tz=timezone.utc).timestamp() # example: 1520020585.536527
NOTE: not all epoch's are alike and using time.time()
will give seconds elapsed since a platform dependent epoch, where as date.timestamp()
gives you what its claims is a POSIX timestamp see caveats below
NOTE: I'm specifically refraining from calling .timestamp()
's output a "POSIX compliant" timestamp. If your application depends on that level of accuracy then you may want to use something other than .timestamp()
NOTE: using datetime.now
as it may give a higher precision
NOTE: we could have omitted the tz
argument above, but it's good habit to use timezone aware dates, as python 3 may make incorrect assumptions when working with naive dates(or not throw errors where we think it would)
Given the timestamp (e.g. 1520020585.536527
), we may convert it to a datetime tz aware object using fromtimestamp
like so:
from datetime import datetime, timezone
ts = 1520020585.536527 # remember me? I'm the epoch example output from above
utc_date = datetime.fromtimestamp(ts, tz=timezone.utc) # outputs: datetime date object
NOTE: fromtimestamp
expects a "POSIX" timestamp, the tz
we supply here is only to avoid naive datetime objects. fromtimestamp
will perform any needed conversion for the timezone we provide, but what timezone is better than UTC, right?
NOTE: also although the python literature explicitly references the input to fromtimestamp()
as a "POSIX" timestamp it is not explicitly referring to the input as "POSIX compliant" and therefore we can only infer what a "POSIX" timestamp is from other parts of its literature, like when it refers to POSIX output as "returned by time.time()"
Upvotes: 1
Reputation: 414585
To convert POSIX timestamp to datetime.datetime
object that represents time in UTC:
from datetime import datetime, timedelta, timezone
timestamp = 1351036517.179364
utc_time = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
# -> 2012-10-23 23:55:17.179363+00:00
If your Python version does not support datetime.timezone
; you could omit it, to get a naive datetime object in UTC.
I need the datetime object to compute time difference between two datapoints, the other datapoint is a datetime object as well.
If naive datetime
objects represent local times that have different UTC offsets than you can't compare them directly otherwise you may get a wrong result. You either need timezone-aware datetime objects or you should convert the datetime objects to UTC first. See
Upvotes: 1
Reputation: 23322
It's worthwhile to remember that a timestamp has no associated timezone information. Unix time is unambiguously UTC, but it's not unusual to store local time in Unix-style timestamps. You must check against a known reference to be sure.
If your timestamps are already in UTC (Unix time), you can use Marc B's suggestion of subtract two unix timestamps directly to give you the number of seconds of difference between them.
You may then want to create a timedelta, which will allow you to easily manipulate datetime
s with it (you can sum or subtract a timedelta to/from a datetime, for example).
datetime.timedelta( seconds= n_seconds )
If your timestamps are in local time, don't subtract them directly, as you'll get potentially incorrect results.
Instead, you should use datetime.fromtimestamp first, attach a timezone to each datetime, and only then subtract them to get the timedelta.
To convert back from a timedelta
to the number of seconds, there's timedelta.total_seconds, assuming you're using python 2.7 . If you have an earlier version, you'll have to do the calculation by hand, or pip install datetime
Upvotes: 3