Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to subtract 2 hours from time formatted as string

My initial string looks like following:

a1 = "06:00:00"
a2 = "01:00:00"

I want to set the time back by two hours.

How to get the following output (in string format)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

a1_new = "04:00:00"
a2_new = "23:00:00"

>Solution :

Here you go!

from datetime import datetime, timedelta

a1 = "06:00:00"

x = datetime.strptime(a1, "%H:%M:%S") - timedelta(hours=2, minutes=0)

y = x.strftime("%H:%M:%S")

print(y)

Steps:

  1. Convert HMS into a DateTime Object
  2. Minus 2 hours from this
  3. Convert the result into a String that only contains Hour Minute & Second
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading