StackGuru
StackGuru

Reputation: 503

How to covert simple date-string to ISO-date format in python?

I'm able to convert ISO-date format to simple date format as below.

from dateutil.parser import parse
date_string = '2018-03-12T10:12:45Z'
dt = parse(date_string)
print(dt.date())    #prints 2018-03-12
print(dt.time())    #prints 10:12:45
print(dt.tzinfo)    #prints tzutc()

How to convert it other way ? examples shown below

If input is `2018-03-12` , then output should be `2018-03-12T00:00:00Z`
If input is `2018-03-12-10-12-45` , then output should be `2018-03-12T10:12:45Z`

I am accepting two inputs (format : yyyy-mm-dd) and trying to form date-range between from-date and to-date in iso-format. How can I do that (as below) ?

input1 : `2018-03-12` , output1 : `2018-03-12T00:00:000Z` (12AM, 24-hr format)
input2 : `2018-03-15` , output2 : `2018-03-15T23:59:000Z` (11:59PM, 24-hr format)

Solution:

import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)

Output:

2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z

Upvotes: 0

Views: 662

Answers (2)

StackGuru
StackGuru

Reputation: 503

Solution:

import dateutil.parser
from datetime import datetime
import time
input1="2018-03-12"
input2="2018-03-15"+" 01:02:03.004"
output1=dateutil.parser.parse(input1)
output2=dateutil.parser.parse(input2)
output1 = "%s:%06.3f%s" % (output1.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output1.second+output1.microsecond / 1e6)),output1.strftime('Z'))
output2 = "%s:%06.3f%s" % (output2.strftime('%Y-%m-%dT%H:%M'),float("%06.3f" % (output2.second+output2.microsecond / 1e6)),output2.strftime('Z'))
print(output1)
print(output2)

Output:

2018-03-12T00:00:00.000Z
2018-03-15T01:02:03.004Z

Upvotes: 0

Alireza
Alireza

Reputation: 706

you can use datetime module (if there is only 2 expected patterns, you can simply do try-except)

str_date = '2018-03-12'

def convert(x):
    try:
        return datetime.strptime(x, '%Y-%m-%d-%H-%M-%S')
    except ValueError:
        return datetime.strptime(x, '%Y-%m-%d')

convert(str_date)

Upvotes: 1

Related Questions