-2

I want to convert my date into DateTime object for MySQL.

My string format is: Mon Aug 27 04:47:45 +0000 2018 Expected Output: 'YYYY-M-D H:mm:ss'

Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • 6
    Possible duplicate of [Most Efficient Way in Python to Convert String with Whitespaces to DateTime for MySql](https://stackoverflow.com/questions/33839738/most-efficient-way-in-python-to-convert-string-with-whitespaces-to-datetime-for) – hiro protagonist Aug 27 '18 at 06:55
  • possible duplicate of [Convert datetime object to a String of date only in Python](https://stackoverflow.com/questions/10624937/convert-datetime-object-to-a-string-of-date-only-in-python) – Aneesh Jose Aug 27 '18 at 06:59

3 Answers3

2
from datetime import datetime
t = datetime.strptime('Mon Aug 27 04:47:45 +0000 2008', '%a %b %d %H:%M:%S %                                                                                                             z %Y')
t.strftime('%Y-%m-%d %H:%M:%S')

Refer section 8.1.8 here

Nisha
  • 39
  • 2
0
from datetime import datetime
date_as_dt_object = datetime.strptime(dt, '%a %b %d %H:%M:%S %z %Y')

You can use date_as_dt_object in a raw query or an ORM. If used in a raw query pass it as a string like:

query = "select * from table where date >" + str(date_as_dt_object)

Check out this list for Python's strftime directives. http://strftime.org/

Nihal Sangeeth
  • 5,168
  • 2
  • 17
  • 32
  • How So? OP says he wants to convert my date into >>DateTime object . – Nihal Sangeeth Aug 27 '18 at 07:16
  • You can't have the expected output in the case of datetime object, edit your answer, I'll remove the downvote – Sushant Aug 27 '18 at 07:20
  • Sure. But it depends on how OP is using it against MySQL. A raw query will yield the correct results against this str(formatted_date). If its an ORM its better to pass a datetime object. – Nihal Sangeeth Aug 27 '18 at 07:31
  • Correct, but the question says *expected format* after conversion, which is not possible – Sushant Aug 27 '18 at 07:33
0

If you are using python 3, this solution would work -

from datetime import datetime
x = 'Mon Aug 27 04:47:45 +0000 2018'
x = datetime.strftime(datetime.strptime(x, '%a %b %d %I:%M:%S %z %Y'), '%Y-%m-%d %H:%M:%S')
# OP '2018-08-27 04:47:45'

But for python 2, you might get a ValueError: 'z' is a bad directive.... In that case, you'll either have to use something like pytz or dateutil. The table that you need to look for all these conversions can be found here

Edit: You can't have Expected Output: 'YYYY-M-D H:mm:ss' if you convert your datetime string to datetime object. Datetime object has it's own format. Above gives you a string of the format that you want

Sushant
  • 3,499
  • 3
  • 17
  • 34