Home > Software engineering >  issue in conversion of date using python
issue in conversion of date using python

Time:04-03

I am very new in python working on dates. I have 2 type of dates (because getting in array dynamically). Something like this ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']

I am trying to get these in this format 17/02/2022 08:29 PM.

Until now trying something like this:

def update_date(datetime):
    date_formating = datetime.strptime(date_time, '%m/%d/%Y %I:%M %p')
    return date_formating

but getting errors like:

ValueError: time data '2022-02-17 08:29:36.345374' does not match format '%m/%d/%Y %I:%M %p'

I need a solution which can turn both formats I am getting into desired format. Any help would be highly appreciated.

CodePudding user response:

Try a list comprehension with datetime.fromisoformat(date_string):

>>> from datetime import datetime
>>> date_strs = ['2022-02-17 08:29:36.345374', '2021-03-18 08:29:36']
>>> [datetime.fromisoformat(s).strftime('%d/%m/%Y %I:%M %p') for s in date_strs]
['17/02/2022 08:29 AM', '18/03/2021 08:29 AM']

CodePudding user response:

The times in the given list come in two different formats

  1. with microseconds
  2. with seconds (and no microseconds)

This code highlights the differences and would work:

import datetime as dt

t = ['2022-02-17 08:29:36.345374' , '2021-03-18 08:29:36']

# format with microseconds
d1 = dt.datetime.strptime(t[0], '%Y-%m-%d %H:%M:%S.%f')

# format with seconds
d2 = dt.datetime.strptime(t[1], '%Y-%m-%d %H:%M:%S')

# format user wants
x = d1.strftime('%m/%d/%Y %I:%M %p')
y = d2.strftime('%m/%d/%Y %I:%M %p')
print(x)
print(y)

The result:

02/17/2022 08:29 AM
03/18/2021 08:29 AM
  • Related