csv.DictWriter:在写入之前转换纪元值

时间:2018-02-22 18:58:47

标签: python

从这本词典中我需要帮助写出"属性"键和值:

[{u'attributes': {u'Ingress1Arrive': 1519133580000L,
                  u'SurveyDate': 1519102800000L,
                  u'globalid': u'fdd28a97-9a28-400d-8284-5ce91868f26e',
                  u'objectid': 3},
  u'geometry': {u'x': -80.09297701660482, u'y': 26.67525376665167}},
 {u'attributes': {u'Ingress1Arrive': 1519136280000L,
                  u'SurveyDate': 1519102800000L,
                  u'globalid': u'cc83f1b4-6335-4659-8463-9d6d50d82bd7',
                  u'objectid': 4},
  u'geometry': {u'x': -80.0929301851895, u'y': 26.67525546250736}},
 {u'attributes': {u'Ingress1Arrive': 1519227780000L,
                  u'SurveyDate': 1519189200000L,
                  u'globalid': u'99ed6b91-6823-4702-868a-2bb4dbd32cbf',
                  u'objectid': 5},
  u'geometry': {u'x': -80.09289801628141, u'y': 26.675340745164966}}]

我需要在写入csv之前将'IngressArrive''SurveyDate'值转换为格式化的日期时间值。下面的代码完全符合我的需要,但输出包含纪元日期值。

with open('C:temp\{}.csv'.format(sheetname), 'wb') as outf:
       dw = csv.DictWriter(outf,  delimiter=",", quotechar="|", fieldnames=['objectid','globalid','SurveyDate','Ingress1Arrive'])
            headers = {}
       for n in dw.fieldnames:
           headers[n] = n
       dw.writerow(headers)
       for row in gdata2:
           dw.writerow(row['attributes'])

1 个答案:

答案 0 :(得分:1)

我不确定你想要的日期/时间格式,所以我猜对了。

>>> import csv
... from datetime import datetime
... 
... 
... def timestamp_to_date(t):
...     return datetime.fromtimestamp(t / 1e3).strftime('%Y/%m/%d %H:%M')
... 
... 
... sheetname = 'test'
... with open('{}.csv'.format(sheetname), 'wb') as outf:
...     dw = csv.DictWriter(
...         outf,
...         quotechar="|",
...         fieldnames=['objectid', 'globalid', 'SurveyDate', 'Ingress1Arrive']
...     )
...     dw.writeheader()
...     for row in gdata2:
...         current = row['attributes']
...         times = {
...             'Ingress1Arrive': timestamp_to_date(current['Ingress1Arrive']),
...             'SurveyDate': timestamp_to_date(current['SurveyDate'])
...         }
...         current.update(times)
...         dw.writerow(current)
... 
>>> with open('test.csv', 'r') as f:
...     for line in f:
...         print(line)
... 
objectid,globalid,SurveyDate,Ingress1Arrive

3,fdd28a97-9a28-400d-8284-5ce91868f26e,2018/02/19 22:00,2018/02/20 06:33

4,cc83f1b4-6335-4659-8463-9d6d50d82bd7,2018/02/19 22:00,2018/02/20 07:18

5,99ed6b91-6823-4702-868a-2bb4dbd32cbf,2018/02/20 22:00,2018/02/21 08:43