1

Say I have two types of datetime format need to check which are the following:

  1. %Y-%m-%dT%H:%M:%S.%f%z
  2. %Y-%m-%d

and convert them to this format %Y-%m-%d %H:%M:%S UTC.

My code at the moment only manage to check one condition :

if val is None:
  val2 = val
else:
  val2 = datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f%z').__format__("%Y-%m-%d %H:%M:%S UTC")

My pseudocode will be :

if val is None:
   val2 = val
elif val is in "%Y-%m-%d" format:
   do this --> val2 = convert from "%Y-%m-%d" to "%Y-%m-%d %H:%M:%S UTC" (eg: 2020-09-01 00:00:00 UTC)
else:
   val2 = datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f%z').__format__("%Y-%m-%d %H:%M:%S UTC")

The time format will be 00:00:00 UTC constantly because there is no timestamp specified in the first place.

user6308605
  • 693
  • 8
  • 26
  • if `%z` in your case means e.g. `+00:00` (with the `:`), you can parse both formats with [fromisoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat) - and then convert to string with strftime. that seems more readable (no conditionals) and [efficient](https://stackoverflow.com/q/13468126/10197418) to me. – FObersteiner Jan 05 '21 at 07:33

1 Answers1

0

May be something like below:

if val is None:
    val2 = val
elif len(val) == 10: 
    #"%Y-%m-%d" format
    val2 = datetime.datetime.strptime(val, "%Y-%m-%d").__format__("%Y-%m-%d %H:%M:%S UTC")
else:
    # Assuming only %Y-%m-%dT%H:%M:%S.%f%z format is possible. 
    # If not add if condition similar to above
    val2 = datetime.strptime(val, '%Y-%m-%dT%H:%M:%S.%f%z').__format__("%Y-%m-%d %H:%M:%S UTC")
PJ47
  • 104
  • 1
  • 10
  • This is nice too. I just thought of this solution `val2 = val+" 00:00:00 UTC"`. Unsure if this is bad but works too. Thank you for helping! – user6308605 Jan 05 '21 at 03:28
  • @user6308605 Both do the same thing. You can pick what feels comfortable for you. – PJ47 Jan 05 '21 at 03:33