user6201066
user6201066

Reputation:

Extract hours and minutes from a string python

I have a string that is in the format of '00:00' displaying the time. It can be any time. I would like to extract the hours and minutes into individual variables.

Upvotes: 6

Views: 23753

Answers (4)

Daniel
Daniel

Reputation: 42748

For parsing times, use the datetime-class:

import datetime
time = datetime.datetime.strptime('23:43', '%H:%M')
print time.hour, time.minute

Upvotes: 5

ForceBru
ForceBru

Reputation: 44828

You may want hours and minutes be integers:

hours, minutes = map(int, "00:00".split(':'))

How this works

  1. str.split(delim) splits a str using delim as delimiter. Returns a list: "00:00".split(':') == ["00", "00"]
  2. map(function, data) applies function to each member of the iterable data. map(int, ["00","00"]) returns an iterable, whose members are integers.
  3. a, b, c = iterable extracts 3 first values of iterable and assigns them to variables called a, b and c.

Upvotes: 16

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9746

If it always in the same format you could split it by the colons:

hours, minutes = "00:00".split(":")

Upvotes: 3

James
James

Reputation: 2711

The split function is your friend here:

>>> time = "11:23"
>>> hours, minutes = time.split(":")
>>> print hours
11
>>> print minutes
23

Upvotes: 1

Related Questions