Gabriel
Gabriel

Reputation: 3

How to read a day and time on the same line?

I was trying to reproduce the following entry in Python: 05 08:12:23.

I did it as follows:

day, hour, minute, second = map (int, input (). Split (':'))

Notice how there is a space after day and the split () I put to separate the numbers with ':'. How would I go about reading the day on the same input? Is there a better way to do this than what I'm trying to do?

The following error ends:

day, hour, minute, second = map (int, input (). split (':'))

ValueError: invalid literal for int () with base 10: '05 08 '

Upvotes: 0

Views: 83

Answers (3)

Tomerikoo
Tomerikoo

Reputation: 19414

You can convert to a datetime object using the strptime class-method with proper format codes:

import datetime

s = "05 08:12:23"
d = datetime.datetime.strptime(s, "%d %H:%M:%S")
print(d.day, d.hour, d.minute, d.second)

Gives:

5 8 12 23

Upvotes: 1

Kraigolas
Kraigolas

Reputation: 5570

If you'd like to do this in one line you can write:

import re 
day, hour, minute, second = re.search(r"(\d\d)\s(\d\d):(\d\d):(\d\d).*", input()).group(1, 2, 3, 4)

What does this do?

  1. re.search searches for the content in your input that matches the pattern given.
  2. (\d\d) means capture two digits, (hence this works only if you have two digits always for each category). Notice \s (space) and the colons are outside the parentheses, which means they are not captured.
  3. Finally, we have 4 matches, so `.group(1, 2, 3, 4) returns a tuple of those four matches in order.

Upvotes: 0

Prune
Prune

Reputation: 77847

You have two different separators on the same line: space and colon. You have to divide the input in two steps:

day, clock = input().split()
hour, minute, second = clock.split(':')

This leaves you with four strings, but you already know how to convert those. :-)

Upvotes: 2

Related Questions