Nillo
Nillo

Reputation: 61

Datetime down to seconds Python

I have a vector like this:

[in]
Dates

[out]
0       2016-04-27 19:56:50
1       2016-04-27 19:56:52
2       2016-04-27 19:56:54
3       2016-04-27 19:56:56
....
9982    2016-04-28 01:29:35

I want to read it as a date time object. I am using:

import datetime as dt

x = [dt.datetime.strptime(d,'%Y-%m-%d %H:%M:%S').date() for d in dates]

But I dont get all of the information. I only get; year,month,day.

[in]
x

[out]
[datetime.date(2016, 4, 27),
 datetime.date(2016, 4, 27),
 datetime.date(2016, 4, 27),
 datetime.date(2016, 4, 27),
 datetime.date(2016, 4, 27), ...]

What shall I do to get hours, mins and seconds into "x" as well?

Upvotes: 0

Views: 227

Answers (2)

Cogumelos
Cogumelos

Reputation: 33

Try:

.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

Upvotes: 0

L3viathan
L3viathan

Reputation: 27273

A datetime.date object is only that detailed. You want a datetime.datetime object instead — just omit the call to .date():

import datetime as dt

x = [dt.datetime.strptime(d,'%Y-%m-%d %H:%M:%S') for d in dates]

Result:

[in]
x

[out]
[datetime.datetime(2016, 4, 27, 19, 56, 50),
 datetime.datetime(2016, 4, 27, 19, 56, 52),
 datetime.datetime(2016, 4, 27, 19, 56, 54),
 datetime.datetime(2016, 4, 27, 19, 56, 56),
 datetime.datetime(2016, 4, 27, 19, 56, 58), ...]

Upvotes: 1

Related Questions