Home > Mobile >  Python flask datetimestamp formatting
Python flask datetimestamp formatting

Time:09-16

So i'm new to python and flask, i'm just wondering if there's a way to format 20210910103255 to 2021/09/10 10:32:55?? I tried using this code. It gets the job done but I want a better way to implement it. This was my code:

"date": as_json['array_id'].split("_")[3][:4]  '/'   as_json['array_id'].split("_")[3][4:6]   '/'   as_json['array_id'].split("_")[3][6:8]
              ' '   as_json['array_id'].split("_")[3][8:10]   ':'   as_json['array_id'].split("_")[3][10:12]   ':'   as_json['array_id'].split("_")[3][12:14]

CodePudding user response:

I think datetime would be the best tool to help you here.

import datetime

x = datetime.datetime.now()
print(x)

More info can be found here https://www.w3schools.com/python/python_datetime.asp

CodePudding user response:

There is nothing wrong with your code, it gets the job done and does not spend unnecessary CPU cycles trying to parse and re-create the timestamp. For cleaner code, try using f-strings:

d = as_json['array_id'].split("_")[3]
"date": f"{d[:4]}/{d[4:6]}/{d[6:8]} {d[8:10]}:{d[10:12]}:{d[12:14]}"

This version is longer, but easier to comprehend:

date = as_json['array_id'].split("_")[3]

year = date[:4]
month = date[4:6]
day = date[6:8]
hours = date[8:10]
minutes = date[10:12]
seconds = date[12:14]

"date": f"{year}/{month}/{day} {hours}:{minutes}:{seconds}"

Or, if you want to go the parsing route, use datetime:

from datetime import datetime

date = as_json['array_id'].split("_")[3]
datetime_object = datetime.strptime(date, "%Y%m%d%H%M%S")
"date": datetime_object.strftime("%Y/%m/%d %H:%M:%S")

CodePudding user response:

You can use the dateutil library for this:

$ pip install python-dateutil

In Python:

>>> import dateutil
>>> dateutil.parser.parse('20210910103255').strftime('%Y/%m/%d %H:%M:%S')
'2021/09/10 10:32:55'
  • Related