Formatting a date time object

Viewed 96

I have the following code:

def parse_contents(contents, filename, last_modified):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            # assume that the user uploaded a CSV file
            df = pd.read_csv(
                io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            # assume that the user uploaded an Excel file
            df = pd.read_excel(io.BytesIO(decoded))
        elif 'txt' or 'tsv' in filename:
            # assume that the user uploaded a TXT file
            df = pd.read_csv(io.StringIO(decoded.decode('utf-8')), delimiter = r'\s+')
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
            ])


    return html.Div([
        html.H5(filename,
            style={'font-family' : 'Arial'}),
        html.H5(datetime.datetime.fromtimestamp(last_modified),
            style={'font-family' : 'Arial'}),


        dash_table.DataTable(
            id='table',
            columns=[{'name': i, 'id': i} for i in df.columns],
            data=df.to_dict('records'),
            sort_action='native',
            filter_action='native',
            page_size= 5,
            style_table={'height' : '300px',
                         'overflowY' : 'auto'},
            style_cell={'width' : '300px',
                        'height' : '30px',
                        'textAlign' : 'left'}
            ),


        ])

When the file is uploaded, the function returns the following (among other things) on the screen:

2020-06-18T19:22:16.374000

I tried the following:

datetime.datetime.strptime(last_modified, '%Y-%m-%d %H:%M:%S.%f')

Which did not work.

What is the best way to convert the output into 06-18-2020 19:22:16.374000?

Thanks!

1 Answers

datetime.datetime.fromtimestamp(last_modified) method returns datetime object so you need to convert from datetime to string.

let returned object
return_value = html.H5(datetime.datetime.fromtimestamp(last_modified))
return_value = 2020-06-18T19:22:16.374000

import datetime
datetime.datetime.strftime(return_value, '%Y-%m-%d %H:%M:%S.%f') # coverting last_modified(datetime object) to string format (%Y-%m-%d %H:%M:%S.%f) 

to know the difference between strptime and strftime formatting datetime

Related