billjay
billjay

Reputation: 13

Converting a list of timestamp strings

I'm trying to convert a list of timestamp strings to to datetime objects. For example I want to convert:

timestamplist

['2020-08-26 11:31:13.669689', '2020-08-26 11:31:13.812931', '2020-08-26 11:31:13.886537']

to this:

[2020-08-26 11:31:13.669689, 2020-08-26 11:31:13.812931, 2020-08-26 11:31:13.886537]

I have tried to use dateutil parser on the list but I can't seem to make it work on the whole list. I have just included the code that brings back the list of timestamp strings here but I'm unsure as to what to write next. I'd appreciate any help given. Thanks in advance.

import scrapy
import sqlite3
import datetime
from dateutil import parser

class A1hrlaterSpider(scrapy.Spider):
    name = '1hrlater'
    conn = sqlite3.connect('ddother.db')
    c = conn.cursor()
    c.execute("SELECT * FROM dd_listings")

    all_database = c.fetchall()

    timestamplist = [x[1] for x in all_database]

    print(timestamplist)

    conn.commit()

    conn.close()

Upvotes: 0

Views: 125

Answers (2)

A.B
A.B

Reputation: 20445

you can do it in the list comprehension itself

import datetime
timestamplist = [datetime.datetime.strptime(x[1], "%Y-%m-%d %H:%M:%S.%f")  for x in all_database]

Upvotes: 1

Hussein Awala
Hussein Awala

Reputation: 5088

from datetime import datetime
string_ts_list = ['2020-08-26 11:31:13.669689', '2020-08-26 11:31:13.812931', '2020-08-26 11:31:13.886537']
ts_list = [datetime.strptime(string_ts,"%Y-%m-%d %H:%M:%S.%f") for string_ts in string_ts_list]

Upvotes: 0

Related Questions