Converting integer to datetime in Python [closed]
Domanda
My code:
import datetime as dt
import scikits.timeseries as ts
ts_start_datetime= ts.Date(freq='T',year=2011,month=1,day=1,hour= 0,minute=0)
ts_end_datetime = ts.Date(freq='T',year=2011,month=12,day=31,hour=23,minute=45)
start_val = ts_start_datetime.value
# 21564001
end_val = ts_end_datetime.value
# 22089586
How do I convert start_val
and end_val
to datetime
objects?
Soluzione
Use datetime.fromtimestamp()
, since your values appear to be minutes rather than seconds, first multiply them by 60:
start_dt = dt.datetime.fromtimestamp(start_val * 60)
end_dt = dt.datetime.fromtimestamp(end_val * 60)
If you want a UTC time instead of a local time, use datetime.utcfromtimestamp()
:
>>> dt.datetime.utcfromtimestamp(21564001 * 60)
datetime.datetime(2011, 1, 1, 0, 1)
>>> dt.datetime.utcfromtimestamp(22089586 * 60)
datetime.datetime(2011, 12, 31, 23, 46)
I'm not exactly sure why each of these are one minute after what you started with, you can always subtract 60 before the call or subtract dt.timedelta(minutes=1)
from the end result.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow