What is the opposite function to utcfromtimestamp()
?
timestamp()
apparently does not take the timezone into account, as one can see in the following example:
import pandas as pd
import datetime
start = pd.datetime(2000, 1, 1, 0, 0, 0)
asFloat = start.timestamp()
startDifferent = datetime.datetime.utcfromtimestamp(asFloat)
startDifferent
Out[8]: datetime.datetime(1999, 12, 31, 23, 0)
You can use the datetime module to convert a datetime to a UTC timestamp in Python. If you already have the datetime object in UTC, you can the timestamp() to get a UTC timestamp. This function returns the time since epoch for that datetime object.
Getting the UTC timestamp datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.
To remove timestamp, tzinfo has to be set None when calling replace() function.
The fromtimestamp() function is used to return the date associated with a given timestamp. The date class's function fromtimestamp() computes and returns the date and time corresponding to a specified timestamp. The timestamps in this example range from 1970 to 2038.
utctimetuple
--> calendar.timegm
--> utcfromtimestamp
forms a round-trip:
import calendar
import datetime as DT
start = DT.datetime(2000, 1, 1, 0, 0, 0)
utc_tuple = start.utctimetuple()
utc_timestamp = calendar.timegm(utc_tuple)
startDifferent = DT.datetime.utcfromtimestamp(utc_timestamp)
print(startDifferent)
# 2000-01-01 00:00:00
timestamp
--> fromtimestamp
also round-trips:
asFloat = start.timestamp()
startDifferent = DT.datetime.fromtimestamp(asFloat)
print(startDifferent)
# 2000-01-01 00:00:00
There is no utc
equivalent of timestamp
which goes directly from a datetime.datetime
to a timestamp. The closest equivalent is calendar.timegm(date.utctimetuple())
.
This roughly depicts the relationship between the methods:
o------------o
| | DT.datetime.utcfromtimestamp (*)
| |<-----------------------------------o
| | |
| | DT.datetime.fromtimestamp |
| datetime |<-------------------------------o |
| | | |
| | .timestamp | |
| |----------------------------o | |
| | | | |
o------------o | | |
| ^ | | |
.timetuple | | | | |
.utctimetuple (*) | | DT.datetime(*tup[:6]) | | |
v | v | |
o------------o o------------o
| |-- calendar.timegm (*) -->| |
| | | |
| |---------- time.mktime -->| |
| timetuple | | timestamp |
| |<-- time.localtime -------| |
| | | |
| |<-- time.gmtime (*)-------| |
o------------o o------------o
(*) Interprets its input as being in UTC and returns output which should be interpreted as being in UTC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With