Python Forum
Convert String to Datetime Object
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert String to Datetime Object
#1
Hi, 

I have the following

myList[0][0]
Output:
'02/28/2017 21:01:00'
type(myList[0][0])
Output:
<class 'str'>
str_date = myList[0][0]
from datetime import datetime
date_date = datetime.strftime(str_date, "%m/%d/%Y %H:%M:%S")
I tried to convert the string object to a datetime object but I got the following error message.

Error:
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
Shouldn't with datetime.strftime method, I would be able to convert the string object to datetime object?

Wonder if someone could please advise.

Thank you!
Reply
#2
not tested:
datetime.datetime.strptime(date_date, "%Y-%m-%d %H:%M:%S.%f")
Reply
#3
(Apr-20-2017, 03:44 AM)tkj80 Wrote: Shouldn't with datetime.strftime method, I would be able to convert the string object to datetime object?

Wonder if someone could please advise.

Thank you!

No, strftime stands for string-from-time
strptime - I would hazard a guess - is string-pparse-to-time
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Formatting DateTime string and and converting it from AM/PM to 24 hours tester_V 2 232 Jun-08-2024, 05:16 PM
Last Post: tester_V
  subtract 2 datetime string jss 4 1,023 Oct-19-2023, 02:42 PM
Last Post: Larz60+
  convert address and broadcast to network object Skaperen 9 2,029 Mar-09-2023, 06:55 PM
Last Post: Skaperen
  convert string to float in list jacklee26 6 2,180 Feb-13-2023, 01:14 AM
Last Post: jacklee26
  Review my code: convert a HTTP date header to a datetime object stevendaprano 1 2,235 Dec-17-2022, 12:24 AM
Last Post: snippsat
  how to convert tuple value into string mg24 2 2,625 Oct-06-2022, 08:13 AM
Last Post: DeaD_EyE
  Convert string to float problem vasik006 8 3,713 Jun-03-2022, 06:41 PM
Last Post: deanhystad
  Convert a string to a function mikepy 8 2,759 May-13-2022, 07:28 PM
Last Post: mikepy
Question How to convert string to variable? chatguy 5 2,801 Apr-12-2022, 08:31 PM
Last Post: buran
  Convert string to int Frankduc 8 2,750 Feb-13-2022, 04:50 PM
Last Post: menator01

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020