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 ?

2 answers 2

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.

  • My Python gives an error ValueError: 'z' is a bad directive in format '%a, %d %b %Y %X %z' when running a script with your code. - faoxis
  • one
    which version of python are you using? - Max
  • 2.7, without +0300 everything is fine - faoxis
  • one
    Yes, there is such a problem . But there is a solution too, I added the answer. - Max

A 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.