0

I have a field in SQL info1[11] it contain the:

DateTime format like this: 2019-01-31 17:30:00

so I wanted to date and time separate so I strip the time like that:

ticket_start_date = str(info1[11])[:10]
output : 2019-01-31

but for the time i am doing this but no luck:

 ticket_start_time = str(info1[11][11:])

I'm getting this error:

TypeError: 'datetime.datetime' object is not subscriptable

Is there any other way to get the time only in this format. The convention to write time is 'hh:mm:ss AM/PM' or 'hh:mm:ss'

I am selenium and SQL with python to automate some task

Nandan
  • 404
  • 2
  • 6
  • 15
  • I think there is an error in the statement 'ticket_start_time = str(info1[11][11:])' change to 'ticket_start_time = str(info1[11])[11:]' – M.J Mar 07 '19 at 06:20
  • no need to do a manual slice, seek `strptime` and `strftime` for "loading string to datatime" or "dump datetime into string", there are good samples at official document, at https://docs.python.org/2/library/datetime.html?highlight=strftime#datetime.date.strftime – Jack Wu Mar 07 '19 at 06:57
  • yeah I didn't see the error. strptime and strftime will be a good approach – Nandan Mar 07 '19 at 07:04
  • i got another error: start_date = datetime.datetime.strptime(_start_date, '%Y-%m-%d') AttributeError: type object 'datetime.datetime' has no attribute 'datetime' – Nandan Mar 07 '19 at 07:09

1 Answers1

2

Perhaps a missing ( in your current approach, should have been:

ticket_start_time = str(info1[11])[11:])

But I wouldn't encourage your current approach of slicing when there are already cooler, shorter and faster ways out there:

Using dparser:

import dateutil.parser as dparser
dt_1 = "2019-01-31 17:30:00"
print("Date: {}".format(dparser.parse(dt_1,fuzzy=True).date()))
print("Time: {}".format(dparser.parse(dt_1,fuzzy=True).time()))

OUTPUT:

Date: 2019-01-31
Time: 17:30:00

EDIT:

From the comments below this answer:

import datetime as dt
start_date = dt.datetime.strptime(_start_date, '%Y-%m-%d')
DirtyBit
  • 16,613
  • 4
  • 34
  • 55