2

Is there any shorter method to translate this ISO 8601 compatible UTC time to the SQL DATETIME format?

>>> str = "2016-03-28T20:23:46+0800"
>>> temp = str.split('T')
>>> temp[1] = temp[1].rstrip('+')
>>> temp[1]
'20:23:46+0800'
>>> temp[1] = temp[1].split('+')[0]
>>> result = " ".join(temp)
>>> result
'2016-03-28 20:23:46'

Thanks!

5
  • I hope you're not planning on formatting or catenating this result to a query string. Commented May 13, 2016 at 12:51
  • I'm planning to write it as a tuple's attribute, yes, and what? Commented May 13, 2016 at 12:53
  • possible duplicate of stackoverflow.com/questions/12281975/… Commented May 13, 2016 at 12:54
  • If by writing it as a tuple's attribute you mean insert it to a table, I mean that manually constructing query strings and passing values by formatting or concatenating them in to the query string is a very bad thing to do. I'm not saying you're doing so, but asking. DB-API's handle passing proper datetime objects as arguments to a placeholder query correctly. Commented May 13, 2016 at 12:57
  • if you use Python bindings for your sql db then it should be able to convert a datetime object automatically i.e., all you need is to convert the string into datetime object. It is more likely that you won't introduce timezone-related errors in this case. Commented May 14, 2016 at 4:24

2 Answers 2

5

You can simply switch formats:

>>> date_str = "2016-03-28T20:23:46+0800"
>>> format = '%Y-%m-%dT%H:%M:%S%z'
>>> new_format = '%Y-%m-%d %H:%M:%S' 
>>> datetime.datetime.strptime(date_str, format).strftime(new_format)
'2016-03-28 20:23:46'

This will not work in python 2.x as it does not support the %z flag. See timezone python 2 support for a workaround

Sign up to request clarification or add additional context in comments.

2 Comments

in Python 2 you will have a problem with the %z. Check this out: stackoverflow.com/questions/12281975/…
@lesingerouge Thanks for noting. I've added the link you provided for python 2.x support.
1

There is no easy way to do this. Checkout this post for more details on possible solutions.

If you're looking for a quick hack try this:

st = '2016-03-28T20:23:46+0800'
st[:19].replace("T", " ")

Or, if you need the date in datetime:

datetime.datetime.strptime(st[:19], '%Y-%m-%dT%H:%M:%S')

1 Comment

>>> str '2016-03-28T20:23:46+0800' >>> import datetime >>> datetime.datetime.strptime(str, "%Y-%m-%d %H:%M:%S").isoformat(" ") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime (data_string, format)) ValueError: time data '2016-03-28T20:23:46+0800' does not match format '%Y-%m-%d %H:%M:%S'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.