0

How can I change the format of a date

var_time="2021-05-17T00:00:00Z" 

to 2021-05-17 00:00:00?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
bbb
  • 149
  • 2
  • 18
  • 2
    You're asking how to replace the capital `T` and drop the `Z`? This is covered in any tutorial on string processing. If this is a `datetime` object -- as it should be, if you need to do this more than once -- then the formatting info is in the package documentation. – Prune Jun 07 '21 at 14:55
  • Why do you need to "convert" anything? `string.split('T')` would get you half way to what you want – OneCricketeer Jun 07 '21 at 14:58
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jun 07 '21 at 15:16

3 Answers3

2

The Data format you have is ISO8601 so you need to convert this to the desired format. Here is what I did:

from datetime import datetime

s= "2021-05-17T00:00:00Z"

yourdate = datetime.fromisoformat(s.replace('Z','+00:00'))
yourdate.strftime('%Y-%m-%d %H:%M:%S')

The Output will be this:

'2021-05-17 00:00:00'

I don't know if this is the best way but I hope I could help.

Source:

shehryar
  • 98
  • 1
  • 8
0

The below should work after taking off the trailing "Z" :

from datetime import datetime
new_var_time = datetime.fromisoformat(var_time[:-1]).strftime("%Y-%m-%d %H:%M:%S")
AmineBTG
  • 597
  • 3
  • 13
0

I am not sure whether your var_time is a string or a time/datetime obeject? If this variable is a string, you can use the following:

import datetime

string = '2021-05-17T00:00:00Z'
date_dt1 = datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%SZ')
print(date_dt1)

print:

2021-05-17 00:00:00
wing
  • 39
  • 1
  • 1
    do not use a literal `Z` in the parsing directive (use `%z` instead) - the Z denotes UTC; if you just ignore it, you'll get naive datetime which Python treats as local time, not UTC. – FObersteiner Jun 07 '21 at 15:18
  • @MrFuppes, you are right. Thank you for the note. – wing Jun 07 '21 at 17:10