There exists some datetime with different string formats in text, for example:
- Tue, 01 Mar 2016 21:17:00 +0800
- 2016/03/01 21:17:00
- 21:17:00 2016/03/01
- 01/03/2016 21:17:00
In order to save or process datetime, we should convert these different formatted time to a format. In this tutorial, we will introduce you how to do in python.
dateutil.parser
We will use python dateutil.parser package to parse different datetime string format. Here is an example code:
import dateutil.parser from datetime import datetime time_str = ['Tue, 01 Mar 2016 21:17:00 +0800', '2016/03/01 21:17:00', '21:17:00 2016/03/01', '01/03/2016 21:17:00'] for t in time_str: d = dateutil.parser.parse(t) print(type(d)) print(d)
Run this code, you will get this output:
<class 'datetime.datetime'> 2016-03-01 21:17:00+08:00 <class 'datetime.datetime'> 2016-03-01 21:17:00 <class 'datetime.datetime'> 2016-03-01 21:17:00 <class 'datetime.datetime'> 2016-01-03 21:17:00
We can find: dateutil.parser.parse() method can convert a string datetime with different formats to a datetime object.
Then we can convert this datatime object to other string format.
Convert datetime to string format
We can use datetime.strftime() to implement it. Here is an example:
time_str = 'Tue, 01 Mar 2016 21:17:00 +0800' d = dateutil.parser.parse(time_str) d = d.strftime("%Y-%m-%d %H:%M:%S") print(d)
Run this code, we will get this result:
2016-03-01 21:17:00
It means we convert ‘Tue, 01 Mar 2016 21:17:00 +0800’ to “%Y-%m-%d %H:%M:%S” format.
Finally, we can save and process datetime easily.