python 3.6 - To take two dates as an integer of 8 digits and print the elapsed date from the earliest date to the later date?

Asked 2 years ago, Updated 2 years ago, 24 views

For example, 20180101 20171231 <- This is input and divided by split, and then

2017.12.31~2018.01.01=1 <- I want to print it out like this.

*Second example.

20160228 20160301 <- Input

2016.02.28-2016.03.01=2 <- Output

I don't know if I should do it or not because of the import datetime, but I can't think of it because my mind is getting complicated. Please.

python

2022-09-21 14:55

1 Answers

Try it in GO language (I've translated the above answers).)

package main

import (
    "fmt"
    "sort"
    "strings"
    "time"
)

func main() {
    temp := "20180101 20171231"
    dates := strings.Split(temp, " ")
    sort.Strings(dates)

    firstDatetime, _ := time.Parse("20060102", dates[0])
    secondDatetime, _ := time.Parse("20060102", dates[1])

    diff := secondDatetime.Sub(firstDatetime)
    out := time.Time{}.Add(diff)

    fmt.Printf("%s~%s=%d\n", dates[0], dates[1], out.Day())
}

20171231~20180101=2


2022-09-21 14:55

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.