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
?
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
?
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)
>>>
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 ...
Use datetime
library to convert datetime string into datetime object by **strptime()**
and from datetime object to datetime strign by **strftime()**
.
Format modes:
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:
srt