Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

69
Views
Using datetime.now gives datetime.datetime error

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.

9 months ago · Santiago Trujillo
1 answers
Answer question

0

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'
9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs