Python csv.DictWriter:写入前转换历元值

Python csv.DictWriter:写入前转换历元值,python,Python,从本词典中,我需要帮助写出属性键和值: [{u'attributes': {u'Ingress1Arrive': 1519133580000L, u'SurveyDate': 1519102800000L, u'globalid': u'fdd28a97-9a28-400d-8284-5ce91868f26e', u'objectid': 3}, u'geometry': {u'x':

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

[{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'])

我不确定你想要什么格式的日期/时间,所以我只是猜测

>>> 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

这就行了!谢谢你,疯狂的勒胡加@用户2309282没问题,很乐意帮助!