Reputation: 7
Somtetimes I see date strings like this "2015-04-09T10:59:22Z"
.
What are "T" and "Z" chars here? How to parse this string by python's time.strptime
?
Upvotes: 0
Views: 909
Reputation: 979
The other answers work and are correct, and yes, "Z" is for Zulu, the old way of referring to UTC.
The problem parsing with the standard library the string, even replacing the Z
with UTC
still renders a time zone naive datetime object. This is a work around I use to create a time zone aware datetime object
from datetime import datetime, timedelta, timezone
time_string = '1582-10-04T12:34:56.789Z'
timeformat = '%Y-%m-%dT%H:%M:%S.%fZ'
datetime.strptime(time_string, timeformat).replace(tzinfo=(timezone(timedelta(0))))
# or in your case
time_string = '2015-04-09T10:59:22Z'
timeformat = '%Y-%m-%dT%H:%M:%SZ' # No microseconds
datetime.strptime(time_string, timeformat).replace(tzinfo=(timezone(timedelta(0))))
Upvotes: 0
Reputation: 36482
strptime
has excellent documentation in its man
page (man strptime
) and on python.org.
You'll have to tell us what the extra characters mean, because we don't know where the string comes from. However, assuming T
and Z
don't mean anything special:
time.strptime(your_date, '%Y-%m-%dT%H:%M:%S%Z')
should do the trick.
EDIT: The Z
is a timezone abbreviation; hence the trailing %Z
.
EDIT2: ah if python's strptime
just understood %Z
. You'll have to ignore it as constant (means UTC, if I'm not totally mistaken)
time.strptime(your_date, '%Y-%m-%dT%H:%M:%SZ')
EDIT3: Zulu time, as I've learned.
Upvotes: 1
Reputation: 114068
from dateutil.parser import parse as date_parse
print date_parse("2015-04-09T10:59:22Z")
it doesnt use strptime ... but you dont need to worry about the date format pretty much ever
(oh yeah you may need pip install python-dateutil
) :P
Upvotes: 1
Reputation: 15433
astr = "2015-04-09T10:59:22Z"
time.strptime(astr, '%Y-%m-%dT%H:%M:%SZ')
## returns time.struct_time(tm_year=2015, tm_mon=4, tm_mday=9, tm_hour=10, tm_min=59, tm_sec=22, tm_wday=3, tm_yday=99, tm_isdst=-1)
Upvotes: 1