-3
xx = str(23-Jun-2019 [8:41:44])

Traceback (most recent call last):  
  File "<pyshell#4>", line 1, in <module>  
    xx = str(23-Jun-2019 [8:41:44])  
NameError: name 'Jun' is not defined 

I am using Python 3 in Windows 7 machine.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
  • 3
    Possible duplicate of [Python NameError: name is not defined](https://stackoverflow.com/questions/14804084/python-nameerror-name-is-not-defined) – itsvinayak Jun 23 '19 at 03:45
  • Unless you are using some sort of `Date` object, you should probably place `23-Jun-2019 [8:41:44]` in between quotes: `'23-Jun-2019 [8:41:44]'`, and not use `str` – Reblochon Masque Jun 23 '19 at 03:46
  • 2
    Not a good dupe @its_vinayak – Reblochon Masque Jun 23 '19 at 03:48
  • 1
    That's not how you define a string. You use quotes. You might as well do it, since you're writing out the literal yourself. :| – cs95 Jun 23 '19 at 03:53

4 Answers4

2

Your code just so happens to work in the weirdest of ways :)

This (xx = str(23-Jun-2019 [8:41:44])) is interpreted as this:

xx = str(23 - Jun - 2019[8:41:44])

It's expecting to get 23 minus Jun (a variable) and then get a slice out of 2019. Because it is working left to right, it gets to 23, sees that it's right, continues on to Jun, and tries to find a variable called Jun.

Because it couldn't find it, it gave a NameError.

What you were probably trying to do is this:

xx = "23-Jun-2019 [8:41:44]"

Python's str can take anything, including numbers, and turns them into something you can output using something like print(). By putting them in a literal, you can make it show what is literal ly there.

GeeTransit
  • 1,458
  • 9
  • 22
1

It is interpreting - as subtraction and Jun as a variable.

You might like to do

xx = "23-Jun-2019 [8:41:44]"

if you intended xx to be a string.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
1

You can't do that unfortunately. To declare string use double quotes. I would also recommend datetime built-in module if you want to work with date and time.

xx = "23-Jun-2019 [8:41:44]"
Roshan
  • 664
  • 5
  • 23
-1

1). Here you are converting 23-Jun-2019 [8:41:44] into a string by str(). While conversion str() is treating Jun as a variable.

2). And if removing the Jun then also the remaining portion is the invalid syntax for PYTHON.

3). USE " " When you have this type of situation. AND use the datetime module instead of [8:41:44].

xx = "23-Jun-2019 [8:41:44]"
Rahul charan
  • 765
  • 7
  • 15