I have a datasets where all the dates have the following format:
2012-10-09T19:00:55Z
I'd like to be able to be able to use methods like .weekday
on them. How do I convert them to the proper format in Python?
I have a datasets where all the dates have the following format:
2012-10-09T19:00:55Z
I'd like to be able to be able to use methods like .weekday
on them. How do I convert them to the proper format in Python?
You can use dateutil.parser.parse
(install with python -m pip install python-dateutil
) to parse strings into datetime objects.
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which you supply a format string to (see Brent Washburne's answer).
from dateutil.parser import parse
a = "2012-10-09T19:00:55Z"
b = parse(a)
print(b.weekday())
# 1 (equal to a Tuesday)
dateutil.parser
. These are the little things that make Python awesome. from somemodule import problemsolver && problemsolver.solvemyspecificproblem()
–
Mantua git clone http://example.com/module/problemsolver problemsolver && cd problemsolver && python problemsolver.py myspecificproblem
–
Downtrend parse
is dates like this: parse("12/11/2017 07:41:27") datetime.datetime(2017, 12, 11, 7, 41, 27)
asumes the first arg is the month parse("13/11/2017 07:41:27") datetime.datetime(2017, 11, 13, 7, 41, 27)
magically makes the first arg the day. All explainable just something you need to know. –
Hygroscopic pip install python-dateutil
. The "python-" part is required! –
Mum This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?
d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()
"%Y-%m-%dT%H:%M:%SZ"
produces a “naive” datetime. To produce an “aware” datetime (i.e., aware of the time zone): "%Y-%m-%dT%H:%M:%S%z"
–
Vermouth You should have a look at moment
which is a python port of the excellent js lib momentjs
.
One advantage of it is the support of ISO 8601
strings formats, as well as a generic "% format" :
import moment
time_string='2012-10-09T19:00:55Z'
m = moment.date(time_string, '%Y-%m-%dT%H:%M:%SZ')
print m.format('YYYY-M-D H:M')
print m.weekday
Result:
2012-10-09 19:10
2
© 2022 - 2024 — McMap. All rights reserved.