0

How to convert a string to the specified datetime format ? For example:

str = 'Wed Mar 16 16:12:05 2016 +0800'   

How can I convert it to : 2016-03-16 16:12:05?

Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
JiangLing
  • 367
  • 1
  • 3
  • 14

3 Answers3

3

Arrow is a great module for doing this in a very straightoforward way: http://crsmithdev.com/arrow/

I perfer arrow to datetime as it is more succinct

For your specific example:

import arrow
date_str = 'Wed Mar 16 16:12:05 2016 +0800'
date = arrow.get(date_str,'ddd MMM D HH:mm:SS YYYY Z')
print date
2016-03-16T16:12:00.050000+08:00
>>> 

Also, it's a bad idea to name strings

str

As this is taken, for the string type!

Why Arrow? I believe it has a nicer api than datetime:

>>> date.humanize()
3: u'2 days ago'
>>> date.resolution
4: datetime.timedelta(0, 0, 1)
>>> date.datetime
5: datetime.datetime(2016, 3, 16, 16, 12, 0, 50000, tzinfo=tzoffset(None, 28800))
>>> date.utctimetuple()
7: time.struct_time(tm_year=2016, tm_mon=3, tm_mday=16, tm_hour=8, tm_min=12, tm_sec=0, tm_wday=2, tm_yday=76, tm_isdst=0)
>>> 
greg_data
  • 2,247
  • 13
  • 20
2

You can do this using strptime :

import datetime
myDatetime=datetime.datetime.strptime(My_string, format)

with format being such as "%Y-%m-%d %H:%M:%S" for Year month day, hour minutes seconds, so in your case it would be 'name of the day, month, day, etc ...

Avión
  • 7,963
  • 11
  • 64
  • 105
Chiappero
  • 53
  • 1
  • 7
2

Use datetime library to convert datetime string into datetime object by **strptime()** and from datetime object to datetime strign by **strftime()**.

Format modes:

  1. %a Weekday as locale’s abbreviated name.
  2. %d Day of the month as a zero-padded decimal number.
  3. %b Month as locale’s abbreviated name.
  4. %H Hour (24-hour clock) as a zero-padded decimal number.
  5. %M Minute as a zero-padded decimal number.
  6. %S Second as a zero-padded decimal number.

more details..

Demo:

>>> from datetime import datetime
>>> result_date =  datetime.strptime('Wed Mar 16 16:12:05 2016', '%a %b %d %H:%M:%S %Y')
>>> result_date
datetime.datetime(2016, 3, 16, 16, 12, 5)
>>> result_date.strftime("%Y-%m-%d %H:%M:%S")
'2016-03-16 16:12:05'

Note:

  1. Do not use reserved word as variable name. e.g. srt
Roman Pokrovskij
  • 9,449
  • 21
  • 87
  • 142
Vivek Sable
  • 9,938
  • 3
  • 40
  • 56