RajeshM
RajeshM

Reputation: 89

Convert Date and Time in required format "Jun 9 18:04:42:"

Current Format is Jun 9 18:04:42:

Required Format is 09/06/2021 18:04:42:00

There is no year in current format, but I need to add it. I have tried following code

s= 'Jun 9 18:04:42:'

'''

  def convert_to_date(s):
    if s!='None':

        if s=='':
            return s
        else:
            print ("to unpack values:",s)
            s=s.replace(' ', ':')

            f_month,f_day,f_hour,f_minute,f_seconds,f_miliseconds = s.split(':')

            s = str(f_month) +'-' + str(f_day) + ' ' + str(f_hour) + ':' + str(f_minute)+':'+str(f_seconds) +':'+str(f_miliseconds)

            print ("unpacked values:",s)

            return s

''' output is: 'Jun-9 18:04:42:'

Upvotes: 0

Views: 47

Answers (1)

Ank
Ank

Reputation: 1714

Use dateutil module's parser.parse method, which can parse a range of differently formatted date strings and return a datetime.datetime object. Then you can convert it to any other format using strftime function:

>>> from dateutil.parser import parse
>>> dt = parse('Jun 9 18:04:42').strftime('%d/%m/%Y %H:%M:%S:00')
>>> print (dt)
09/06/2021 18:04:42:00

Upvotes: 1

Related Questions