当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Convert Unicode Object to a Datetime Object in a List of a List

问题描述:

I am trying to take a list of a list and I would like to split apart the datetime object that is in the first element of each element of the list as shown below.

list = [[u'2014-09-02T23:00:00', 1, 1, u'msdn.microsoft.com', u'Engineering & Technology', 1], [u'2014-09-02T23:00:00', 1, 1, u'qr.ae', u'Uncategorized', 0], [u'2014-09-02T23:00:00', 1, 1, u'accounts.google.com', u'General Communication & Scheduling', 0]]

I saw the previous Stack question about Unicode to Dates (link) and have tried the following code:

date_unicode = str(list[0].split('T'))

date = datetime.strptime(date_unicode, '%Y-%m-%dT%H:%S')

only to receive an error saying the module object has no attribute 'strptime.' If someone would be able to help me not only split the unicode dates into actual date objects for each element of the list I would really appreciate it.

网友答案:
  1. Your list is two-diminsional, so you need an extra index: list[0][0].
  2. Your strptime() format accepts the entire ISO8601 date, so you don't need .split()
  3. strptime() is a method of datetime.datetime
date_unicode = str(list[0][0])
date = datetime.datetime.strptime(date_unicode, '%Y-%m-%dT%H:%M:%S')
print date

Finally, you have several elements of the list, so you'll need a loop:

newlist = [datetime.datetime.strptime(item[0], '%Y-%m-%dT%H:%M:%S')
           for item in list]
print newlist
网友答案:
from datetime import datetime
print [datetime.strptime(x[0],"%Y-%m-%dT%H:%M:%S") for x in l]
[datetime.datetime(2014, 9, 2, 23, 0), datetime.datetime(2014, 9, 2, 23, 0), datetime.datetime(2014, 9, 2, 23, 0)]

You need to use from datetime import datetime or else datetime.datetime.strptime

分享给朋友:
您可能感兴趣的文章:
随机阅读: