8.1 datetime Basic date type and time type (Python3.3)
Use strptime () to create a datetime object from a string.
from datetime import datetime
>>> t = datetime.strptime('2014/01/01 00:01:02', '%Y/%m/%d %H:%M:%S')
>>> t.strftime('%Y/%m/%d %H:%M:%S')
'2014/01/01 00:01:02'
As you can see in the reference URL, the date object does not have a strptime () method. Therefore, ** The following method is useless. ** **
This is an error
>>> from datetime import date
>>> t = date.strptime('2014/01/01', '%Y/%m/%d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.date' has no attribute 'strptime'
To create a date object from a string
Create a datetime object with strptime () of datetime
Create a date object from the generated datetime object
It seems good to take the method.
>>> from datetime import datetime
>>> t = datetime.strptime('2014/01/01', '%Y/%m/%d')
>>> t.isoformat() #At this stage, the time part is initialized with 0
'2014-01-01T00:00:00'
>>> date = t.date()
>>> date.isoformat()
'2014-01-01'
Creating a time object from a string can be done in the same way as creating a date object from a string.
>>> from datetime import datetime
>>> t = datetime.strptime('13:14:15', '%H:%M:%S')
>>> t.isoformat() #At this stage, the date part has been initialized on January 1, 1900.
'1900-01-01T13:14:15'
>>> t = t.time()
>>> t.isoformat()
'13:14:15'
Recommended Posts