Reputation: 43
I have to convert time in seconds from 1904 in python. I have found a solution, but it's not giving the expected results.
In fact I don't understand how python converts time, because I did this job with a shell script and the answer is not the same in python.
An example in shell:
origine=$(date -d '1904-01-01 00:00:00 +0000' '+%s')
T0day=${origine#-}
Tday= $(date -d '2011-10-06 18:05:56 +0000' '+%s')
echo "obase=16;"$Tday+$T0day"" | bc
If you try to do it in python like this:
dt=datetime.datetime(2011, 10, 06, 18, 05,56)
t1=int(time.mktime(dt.timetuple()))
dt=datetime.datetime(1904, 1, 1, 0, 0, 0)
t2=int(time.mktime(dt.timetuple()))
t3= int(t1+t2)
print (hex(t3))
Result in shell: CAB39E84
Result in python: CAB38264
Is there a better coding solution in python?
Upvotes: 4
Views: 1134
Reputation: 18007
Use timedelta.total_seconds()
,
import datetime
dt_base = datetime.datetime(1904, 1, 1, 0, 0, 0)
dt = datetime.datetime(2011, 10, 06, 18, 05, 56)
total_seconds = (dt - dt_base).total_seconds()
print(total_seconds)
# 3400769156.0
Upvotes: 2