TLDR
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.
Given a UNIX / EPOCH Timestamp
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)
Convert Timestamp to datetime object
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()"