I have a set of variables(epoch_time,normal_date,date_time,date_time_zone) which can be passed randomly and based on the string format, I am converting it into my required date format (%Y-%m-%d). My variable can be a string with epoch value or string with date timezone or string with datetime or only date. I have tried the following way and it is always going into the first item only in allowed_date_formats. Can someone suggest me a better approach or help me in resolving the issue.
from datetime import datetime
epoch_time='1481883402'
normal_date="2014-09-03"
date_time=str("2014-05-12 00:00:00")
date_time_zone=str("2015-01-20 08:28:16 UTC")
OP_FORMAT="%Y-%m-%d"
ALLOWED_STRING_FORMATS=["%Y-%m-%d %H:%M:%S %Z","%Y-%m-%d %H:%M:%S","%Y-%m-%d"]
def convert_timestamp(date_timestamp=None):
for format in ALLOWED_STRING_FORMATS:
if datetime.strptime(date_timestamp,format):
d=datetime.strptime(date_timestamp,"%Y-%m-%d")
else:
d = datetime.fromtimestamp((float(date_timestamp) / 1000.), tz=None)
return d.strftime(OP_FORMAT)
print(convert_timestamp(normal_date))
Error that i am getting is
ValueError: time data '2014-09-03' does not match format '%Y-%m-%d %H:%M:%S %Z'
%H:%M:%S %Zfrom2014-09-03?tryandexceptabove theif datetime.strptime(date_timestamp,format):andelse:.