Reputation: 129
I am trying to the parse dates of the format '2016-04-15T12:24:20.707Z' in Python, tried strptime, doesn't work and I also tried django parse_datetime but it only returns none as the value
Upvotes: 10
Views: 14433
Reputation: 3616
You may try this way if you need something on the fly:
This returns the current datetime in UTC, as a datetime object then immediately converts it to your preferred custom format.
from datetime import datetime, timezone
from time import strftime
# Get UTC Time datetime object and convert it to your preferred format.
print(f"Regular : { datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') }") # Regular : 2022-06-04 23:08:27
print(f"Log Format: { datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S') }") # Log Format: 20220604_230827
print(f"YMD Format: { datetime.now(timezone.utc).strftime('%Y-%m-%d') }") # YMD Format: 2022-06-04
print(f"Time Format: { datetime.now(timezone.utc).strftime('%H:%M:%S') }") # Time Format: 23:08:27
# Without the f'String'
print(datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')) # Regular : 2022-06-04 23:08:27
print(datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')) # Log Format: 20220604_230827
print(datetime.now(timezone.utc).strftime('%Y-%m-%d')) # YMD Format: 2022-06-04
print(datetime.now(timezone.utc).strftime('%H%M%S')) # Time Format: 23:08:27
# Details:
# Get current DateTime in UTC
datetime.now(timezone.utc)
# datetime.datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=datetime.timezone.utc)
type(datetime.now(timezone.utc))
# <class 'datetime.datetime'>
# Use the strftime on the datetime object directly
datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
# '2022-06-04 23:13:27'
type(datetime(2022, 6, 4, 23, 13, 27, 498392, tzinfo=timezone.utc).strftime('%Y-%m-%d %H:%M:%S'))
# <class 'str'>
Upvotes: 0
Reputation: 2950
You may try this way :
from datetime import datetime
date_str = '2016-04-15T12:24:20.707Z'
date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(date)
Output:
2016-04-15 12:24:20.707000
Upvotes: 15
Reputation: 88459
You have to specify the format as "%Y-%m-%dT%H:%M:%S.%fZ"
while conversion
In [11]: from datetime import datetime
In [12]: out_format = "%Y-%m-%d"
In [13]: input_format="%Y-%m-%dT%H:%M:%S.%fZ"
In [14]: date_time_obj = datetime.strptime(time,input_format)
In [15]: date_time_obj
Out[15]: datetime.datetime(2016, 4, 15, 12, 24, 20, 707000)
In [16]: date_time_str = date_time_obj.strftime(out_format)
In [17]: date_time_str
Out[17]: '2016-04-15'
Upvotes: 3
Reputation: 541
This seems to be working alright:
import dateparser
dateparser.parse('2016-04-15T12:24:20.707Z')
> datetime.datetime(2016, 4, 15, 12, 24, 20, 707000, tzinfo=<StaticTzInfo 'Z'>)
Upvotes: 0
Reputation: 6556
import dateutil.parser
from datetime import datetime
dt = dateutil.parser.parse('2016-04-15T12:24:20.707Z')
Upvotes: 0