简体   繁体   中英

Converting values of dictionary to the timestamp format

I have the dictionary like this:

>>print xdict 
{'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21), ..., ...]}

Is it a way to transform those values to timestamp format? I wanted to be exactly like this:

print xdict
{'time': [1433320863.0, 1433356341.0, ..., ...]}

Your time tuples do not represent time in UTC. If it is your local timezone and the utc offset rules for the corresponding times are the same as they are now or if C time library has access to a historical time zone database on your platform then you could pass the time tuples to time.mktime() to get "seconds since epoch":

#!/usr/bin/env python
import time

x = {'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21)]}
x['time'] = [time.mktime(tt + (-1,)*3) for tt in x['time']]

Otherwise, you should use pytz to get access to the tz database on all platforms and compute the correct "seconds since the Epoch" (POSIX timestamp) corresponding to the input time tuples:

#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone() # pytz tzinfo representing local time
epoch = datetime(1970, 1, 1, tzinfo=pytz.utc)
x = {'time': [(2015, 6, 3, 10, 41, 3), (2015, 6, 3, 20, 32, 21)]}
x['time'] = [(local_timezone.localize(datetime(*tt), is_dst=None) - epoch).total_seconds()
             for tt in x['time']]

Loop through the list and excute the code below. You need time.mktime in order to change into seconds

import time
import datetime

a = (2015, 6, 3, 10, 41, 3)

b = datetime.datetime.strptime(', '.join(str(x) for x in a),'%Y, %m, %d, %H, %M, %S')

print(time.mktime(b.timetuple()))

>>> 1433342463.0

Initialize datetime.datetime with unpacked tuple(over * operator). Then using map and lambda you can easily get your goal.

import time
import datetime

def transform(xdict):
  return {"time": map(lambda k: time.mktime(datetime.datetime(*k).timetuple()), xdict["time"])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM