0

I have the following string in Python:

2023-07-03T14:30:00.000Z

How can I extract the hour and minute from this string in the most elegant way?

edn
  • 1,981
  • 3
  • 26
  • 56
  • 1
    Does this answer your question? [Convert string "Jun 1 2005 1:33PM" into datetime](https://stackoverflow.com/questions/466345/convert-string-jun-1-2005-133pm-into-datetime) – Zero Jul 03 '23 at 19:05
  • 1
    What's the problem? What have you tried? Sounds like a problem of computer science that has been solved before. Also: which hour do you want? The hour as given, which might be any timezone? The local hour of the PC running the code? UTC hour? – Thomas Weller Jul 03 '23 at 19:05
  • use [fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) to parse the string (see [this](https://stackoverflow.com/a/62769371/10197418) for Python < 3.11), then use the `hour` and `minute` attributes of the resulting datetime object. – FObersteiner Jul 04 '23 at 06:24

2 Answers2

1

I think this way is the most elegant.

from dateutil.parser import parse
s = "2023-07-03T14:30:00.000Z"
dt = parse(s)
hour = dt.hour
minute = dt.minute
Pluto
  • 4,177
  • 1
  • 3
  • 25
0

One way to do it is as follows:

from datetime import datetime
dts= "2023-07-03T14:30:00.000Z"
dto = datetime.strptime(dts[:-5], "%Y-%m-%dT%H:%M:%S")
hour = dto.hour
minute = dto.minute
AlefiyaAbbas
  • 235
  • 11