Home > Software design >  How do I get rid of the year, month, and day?
How do I get rid of the year, month, and day?

Time:10-27

I was trying to write a program that converts a string to datetime type. The code looks like this.

import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p)

and the output was

1900-01-01 20:36:00

How do I get rid of the '1990-01-01' ?

CodePudding user response:

It's unfortunate that you cannot simply write

p = datetime.time.strptime(time, "%H:%M")

because time.strptime is not defined. You are forced to use datetime.strptime, which returns a datetime object no matter what fields are actually being parsed.

On the plus side, you can get the time object you want relatively easily.

t = p.time()
print(t)  # Outputs 20:36:00

CodePudding user response:

You're creating a datetime object from your string and displaying the datetime as a whole.

What you should do:

display just the time part:

  1. use strftime:

The code

import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.strftime("%H:%M"))
  1. use time:

The code:

import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.time())

What you really should do:

Create a time object from your data. For that you can use datetime.time

import datetime
time="20:36"
hour, minute = time.split(":")

t = datetime.time(hour=int(hour), minute=int(minute))
print(t)
  • Related