I have a date string in this format:
Thu, 18 Aug 2016 11:38:41 +0300 How to translate it to this type YYYY-MM-DD hh:mm:ss ?
Starting with python 3.2 :
from datetime import datetime # Переводим строку в объект datetime d = datetime.strptime('Thu, 18 Aug 2016 11:38:41 +0300', '%a, %d %b %Y %X %z') # Получаем из объекта строку в нужном формате print(str(d.strftime('%Y-%m-%d %X'))) For earlier versions, you can use the dateutil library:
pip install python-dateutil To display the date in the desired format, use the same way:
from dateutil.parser import parse d = parse('Thu, 18 Aug 2016 11:38:41 +0300') print(str(d.strftime('%Y-%m-%d %X'))) For more information about what other format manipulations you can do, see the bottom of this documentation.
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %X %z' when running a script with your code. - faoxis+0300 everything is fine - faoxisA similar date format is used in email, so you can use the email module from the standard library to use:
>>> from email.utils import parsedate >>> tt = parsedate('Thu, 18 Aug 2016 11:38:41 +0300') >>> tt (2016, 8, 18, 11, 38, 41, 0, 1, -1) >>> import time >>> time.strftime('%Y-%m-%d %H:%M:%S', tt) '2016-08-18 11:38:41' The code works on both Python 2 and 3.
The accepted format for the strftime() function may depend on the platform (on C strftime(3) ). If portability is needed, then ensure that the codes used are supported on the desired platforms.
Source: https://ru.stackoverflow.com/questions/556678/
All Articles