-1

I am writing a UI automated test that checks a date in the database and returns the date as a string in this format 1975-07-14T16:32:47.000Z and comparing it to the date that is displayed on the webpage but the date on the webpage is in this format Day-Month name-Year (14 July 1975), therefore I need to convert the date return by the database to Day-Month name-Year (14 July 1975) so that I am comparing like for like. How do I change the date string to the format I need

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Pmcg1983
  • 19
  • 6

2 Answers2

2

You can use dateutil.parser to parse the string you got from the datebase into a datetime.datetime, which in turn can be formatted using strftime:

import dateutil.parser

input="1975-07-14T16:32:47.000Z"

dt = dateutil.parser.parse(input)

print(dt.strftime("%d %B %Y"))
MSpiller
  • 3,500
  • 2
  • 12
  • 24
0
from datetime import datetime
dt_string = "1975-07-14T16:32:47.000Z"
datetime_object = datetime.strptime(dt_string, "%Y-%m-%dT%H:%M:%S.%fZ")
new_datetime_string = datetime.strftime(datetime_object, "%d-%B-%Y")
print(new_datetime_string)
# prints "14-July-1975"

We are using datetime module where datetime.strptime will generate a datetime object where you can call .date(),.time(),.today() and other functions but to get back to string as per the given format of Day-Month Name-Year datetime.strftime()(stringify time) is used. This converts datetime obj to given format of datetime string.

  • %d - date (DD - 01,02,...,31)
  • %m - month (MM - 01,02,...,12)
  • %Y - Year (YYYY - 2022,2021,...)
  • %B - Full Month Name (January, Feburary,..)
  • %f - Milliseconds

you can find out more in following link: Datetime format codes