Reputation: 8714
I am trying to convert time into specific format using following code:
datetime.datetime.strptime(timezone.now() + timedelta(days=14), '%Y-%m-%dT%H:%M:%S.%f%z')
I am getting error that the first parameter has to be string.
I also tried using this code
datetime.datetime.strptime(str(timezone.now() + timedelta(days=14)), '%Y-%m-%dT%H:%M:%S.%f%z')
But then I am getting following error:
time data '2017-06-04 14:26:18.941458+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'
Can someone suggest how can I convert to the specific format. Thanks!
Upvotes: 2
Views: 566
Reputation: 9235
If you are trying to convert the datetime.datetime() object into string, you could just do this,
>>> datetime.datetime.strftime(timezone.now() + timedelta(days=14), '%Y-%m-%dT%H:%M:%S.%f%z')
'2017-06-04T14:45:23.621658+0000'
Or if you want it as the datetime object,
>>> datetime.datetime.strptime(str(timezone.now() + timedelta(days=14))[:26], '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2017, 6, 4, 14, 50, 26, 5649)
Upvotes: 1
Reputation: 1074
Django has a built in date parser that abstracts the logic of strftime
away called parse_datetime. You can simply pass in a date string and it will return a datetime.datetime
object. Here's what your code would look like:
from django.utils.dateparse import parse_datetime
parse_datetime(str(timezone.now() + timedelta(days=14)))
>>> datetime.datetime(2017, 6, 4, 7, 45, 28, 301957)
Upvotes: 1