1

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'
2
  • Where it will get you the %H:%M:%S %Z from 2014-09-03? Commented Oct 18, 2018 at 21:07
  • If you want to avoid error(e.g. if format can't be used) you should use try and except above the if datetime.strptime(date_timestamp,format): and else:. Commented Oct 18, 2018 at 21:09

2 Answers 2

5

You can use try-except for this.

def convert_timestamp(date_timestamp, output_format="%Y-%m-%d"):
    ALLOWED_STRING_FORMATS=[
        "%Y-%m-%d %H:%M:%S %Z",
        "%Y-%m-%d %H:%M:%S",
        "%Y-%m-%d",
    ]

    for format in ALLOWED_STRING_FORMATS:
        try: 
            d = datetime.strptime(date_timestamp,format):
            return d.strftime(output_format)
        except ValueError:
            pass
    try:
        # unix epoch timestamp
        epoch = int(date_timestamp) / 1000
        return datetime.fromtimestamp(epoch).strftime(output_format)
    except ValueError:
        raise ValueError('The timestamp did not match any of the allowed formats')
Sign up to request clarification or add additional context in comments.

2 Comments

my string contains epoch format as well, can u pls help with that condition also
I've added epoch case at the end of the function. I initially thought python strptime might support the epoch %s format (lowercase s), but it doesn't. strftime, on the other hand, uses the platform C library, so it does support %s, at least on linux.
1

Do you need to make sure that only specific formats are allowed?

Otherwise you might consider using the automatic parser from dateutil:

from dateutil import parser
normal_date="2014-09-03"
print(parser.parse(normal_date))

1 Comment

Thanks for the answer but I would like to consider python default module only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.