Reputation: 15180
If I print a datetime
object in python with a simple print myDateTime
(or print(myDateTime)
in python3), how can I recover the datetime
object from the resulting string?
I could have asked "what is the python strftime
format used by datetime.__str__()
"?
ps: There are many questions about conversion of strings to python datetime objects. In the spirit of using stack overflow as a repository of quickly available, useful programming tips, I'm asking this since none of those questions answer this rather specific and oft needed query.
Upvotes: 1
Views: 724
Reputation: 414225
By definition, str(datetime_obj)
is datetime_obj.isoformat(' ')
. There is no method that would parse the ISO 8601 format back; you have to provide the format to strptime()
explicitly:
>>> from datetime import datetime, timezone
>>> now = datetime.now(timezone.utc)
>>> s = str(now)
>>> s
'2015-04-06 10:31:08.256426+00:00'
>>> s[:26]
'2015-04-06 10:31:08.256426'
>>> datetime.strptime(s[:26]+s[26:].replace(':',''), '%Y-%m-%d %H:%M:%S.%f%z')
datetime.datetime(2015, 4, 6, 10, 31, 8, 256426, tzinfo=datetime.timezone.utc)
%z
supports +HHMM
but it doesn't support +HH:MM
that is why the replace()
call is used here.
datetime.timezone
is available since Python 3.2. For older versions, see
Upvotes: 2
Reputation: 15180
If the datetime object doesn't have timezone info (perhaps interpreted as UTC time), you can do something like this (python 2 in this case, but the same in python 3):
import datetime
unprintStrptimeFmt = "%Y-%m-%d %H:%M:%S.%f"
d = datetime.datetime.utcnow()
print d
# produces e.g.: 2015-04-06 03:11:23.840526
dd = datetime.datetime.strptime("2015-04-06 03:11:23.840526",unprintStrptimeFmt)
print dd == d
# produces: True
Upvotes: 1