4

I am using Python. My time format is like

2020-05-23T06:35:11.418279Z #May 23, 2020 at 12:05:11 PM GMT+05:30

I want to convert into human readable time like

23-05-2020 12:05 PM

I tried parser too. But no effect.

Can anyone help me with this?

Thanks in advance :)

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
codebuff
  • 93
  • 3
  • 15

2 Answers2

5

See also How do I parse an ISO 8601-formatted date?

Unfortunately, a string as '2020-05-23T06:35:11.418279Z' cannot be parsed directly with the built-in fromisoformat (Python 3.7+) due to the Z. You can use strptime instead, or this workaround, or dateutil's parser. Ex:

from datetime import datetime
import dateutil

s = '2020-05-23T06:35:11.418279Z'

### parsing options
# strptime
dt = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
# alternatively fromisoformat with replace (most efficient)
dt = datetime.fromisoformat(s.replace('Z', '+00:00'))
# or more convenient and a bit less efficient:
dt = dateutil.parser.isoparse(s)

# change timezone to Indian Standard Time:
dt = dt.astimezone(dateutil.tz.gettz('Asia/Kolkata'))
# datetime.datetime(2020, 5, 23, 12, 5, 11, 418279, tzinfo=tzfile('Asia/Calcutta'))

# note for Python 3.9+:
# use zoneinfo from the standard lib to get timezone objects

# now format to string with desired format
s_out = dt.strftime('%Y-%m-%d %I:%M %p')
s_out
# '2020-05-23 12:05 PM' 
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
1
import datetime, pytz
isodate = '2020-05-23T06:35:11.418279Z'
d = datetime.datetime.fromisoformat(isodate[:-1]).replace(tzinfo=pytz.utc) # we need to strip 'Z' before parsing
print(d.astimezone(pytz.timezone('Asia/Kolkata')).strftime('%d-%m-%Y %I:%M %p'))
Błotosmętek
  • 12,717
  • 19
  • 29
  • It is perfectly working fine dood.Thanks you so much.But what is it mean isodate[:-1] – codebuff May 23 '20 at 09:18
  • `isodate[:-1]` is `isodate` without the last character (which is Z, which does not conform to strict ISO format) – Błotosmętek May 23 '20 at 09:19
  • I have one more doubt.Don't mistaken me.Because these time stuffs are so much confusing me. We are adding timezonr('Asia/Kolkata').What If suppose my customers are from america or europe. – codebuff May 23 '20 at 09:31
  • 1
    Then use appriopriate time zone. You wanted `GMT+05:30`, that's India time. You can check the list of available timezone names by `print(pytz.all_timezones)` – Błotosmętek May 23 '20 at 11:50