4

so i've been on the python language making stuff. I encounter some error which is not so understandable:

TypeError: 'datetime.datetime' object is not subscriptable

(I think) this is the code that cause it:

def brew():
    # Get UTC time
    curr_dt = datetime.now(timezone.utc)
    # Slice it
    curr_dt = curr_dt[0:19]
    # Print
    print(curr_dt)

What am I doing wrong? I just want to get the date and time in 2022-01-04 14:25:10.860837+00:00 by slicing it. Is there a solution of how to get rid of error or even comes with more easy and/or practical ways? Thank You for Your time.

3
  • 2
    you have a datetime object curr_dt - you can't subscript that (the [0:19] part). Convert to string first, e.g. datetime.now(timezone.utc).isoformat(' ')[:19]. Commented Jan 4, 2022 at 14:33
  • Maybe you want strftime() ? Commented Jan 4, 2022 at 14:33
  • 3
    Use datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S') or str(datetime.now(timezone.utc))[:19] Commented Jan 4, 2022 at 14:35

1 Answer 1

3

Use the following code:

from datetime import datetime, timezone

def brew():
    # curr_dt = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
    curr_dt = str(datetime.now(timezone.utc))[:19]
    print(curr_dt)

Output:

>>> brew()
'2022-01-04 14:35:04'
Sign up to request clarification or add additional context in comments.

Comments

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.