I cannot understand why this is failing, can someone please explain:
import datetime
def test(timestamp):
xt = datetime(2013, 4,4)
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
The error is:
Traceback (most recent call last):
File "", line 12, in
File "", line 5, in test
TypeError: 'module' object is not callable
It seems to work ok with from datetime import datetime instead. I can't understand what the difference is.
Thanks.
Because in the datetime module, there is a datetime() function, but you didn't call it ( you instead tried to call the module, that's why you got a TypeError: 'module' object is not callable).
import datetime
def test(timestamp):
xt = datetime(2013, 4,4) # Problem is this line.
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
To fix the line, change it to:
xt = datetime.datetime(2013,4,4)
The reason from datetime import datetime worked was because you imported the specific function, and so you wouldn't need to do datetime.datetime().
datetime is both a module AND a class in that module. In your example you need datetime.datetime.
The
xt = datetime(2013, 4,4)
should be
xt = datetime.datetime(2013, 4,4)
Here, datetime is the name of the module. The full name of the class is datetime.datetime.
datetime is the datetime module, datetime.datetime is the datetime type:
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
Here datetime can refer to the module or the class within the module so you have to disambiguate
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
gives the following output:
(datetime.datetime(2013, 4, 4, 0, 0), datetime.datetime(2013, 4, 4, 8, 37, 20))
Related
I have the following function in my utils.py basically count the seconds from 1970 till curent time:
import datetime
def get_utc_timestamp():
d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970, 1, 1)
t = (d - epoch).total_seconds()
return t
I want to run a test case on that function but it's time dependent so i looked for a solution and stumble upon this question on SO link i tried to apply it in my test_utils.py:
import unittest
from utils import *
from unittest import mock
import datetime
class TestUtils(unittest.TestCase):
#mock.patch('utils.datetime.datetime')
def test_get_utc_timestamp(self, mock_dt):
mock_dt.utcnow = mock.Mock(return_value = datetime.datetime(2019, 8, 27, 8, 52, 12, 703618))
result = get_utc_timestamp()
self.assertEqual(result, 1566895932.703618)
if __name__ == '__main__':
unittest.main()
I tested the result of it in the console:
d = datetime.datetime(2019, 8, 27, 8, 52, 12, 703618)
epoch = datetime.datetime(1970, 1, 1)
t = (d - epoch).total_seconds()
return t
And it returned
1566895932.703618
But when i run the test i got AssertionError:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/unittest/mock.py", line 1179, in patched
return func(*args, **keywargs)
File "/app/tests/test_utils.py", line 15, in test_get_utc_timestamp
self.assertEqual(result, 1566895932.703618)
AssertionError: <MagicMock name='datetime().__sub__().total_seconds()' id='140475857850040'> != 1566895932.703618
What am i doing wrong ?
Any help would be appreciate!
EDIT:
thank ipaleka for the explanation on what going on, since i can't change python built - in class with mock so i need to make a custom class of utcnow() to return the custom time in test_utils.py:
class NewDate(datetime.datetime):
#classmethod
def utcnow(cls):
return cls(2019, 8, 27, 8, 52, 12, 703618)
datetime.datetime = NewDate
and change test function to:
def test_get_utc_timestamp(self):
result = get_utc_timestamp()
self.assertEqual(result, 1566895932.703618)
You're not doing anything wrong related to referenced SO answer, but that example uses only utcnow function while you're using both utcnow and datetime (for creating epoch variable).
When you patch a module then every call to submodule, method or its function creates a MagicMock. That happens when you called epoch = datetime.datetime(1970, 1, 1). So basically you're comparing MagicMock to float.
You should either patch them both or patch just the utcnow with:
#mock.patch('utils.datetime.datetime.utcnow')
def test_get_utc_timestamp(self, mock_dt):
mock_dt.return_value = datetime.datetime(2019, 8, 27, 8, 52, 12, 703618)
result = get_utc_timestamp()
self.assertEqual(result, 1566895932.703618)
I received the datetime in below format
timestamp = '2019-03-18 01:50:00 -0800'
and wanted to convert into datetime in python
i tried but won't able to pick the UTC offset
from datetime import datetime
from datetime import timedelta
timestamp = '2019-03-18 01:50:00 -0800'
date_format = '%Y-%m-%d %H:%M:%S %z'
d_t =datetime.strptime(timestamp,date_format)
Error i get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
how to pick UTC offset in python 2.7?
Just use dateutil
from dateutil import parser
obj = parser.parse('2019-03-18 01:50:00 -0800')
print(obj)
#2019-03-18 01:50:00-08:00
Install pytz library
sudo easy_install --upgrade pytz
Import pytz to code
from datetime import datetime
from pytz import timezone
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") #parse only date & time
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC')) #get time zone using pytz
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")
It should help.
I have a python script
import urllib2
from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(date,month,year):
today = date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
But i get this error-
Traceback (most recent call last):
File "test.py", line 17, in <module>
print generateDateList(4,12,2017)
File "test.py", line 11, in generateDateList
today = date(year, month, date)
TypeError: 'int' object is not callable
Why is it failing? I substituted the function with values and it worked. Should i convert the function inputs to integer again?
This line - def generateDateList(date,month,year):
The name of the first argument date shadows the name date imported at the top. You need to rename the argument to something like day inside your function.
As written, date is actually an integer you pass to the function, and calling it results in an error you are seeing.
Two options.
Option No.1 (import datetime):
import datetime
def generateDateList(date, month, year):
today = datetime.date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.datetime.strftime(today + datetime.timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4, 12, 2017)
Option No.2 (rename date parameter to day):
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(day,month,year):
today = date(year, month, day)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
The problem is the fact you have a parameter with the same name of the date() function.
I have the following vars:
time_created = datetime.utcnow() and time_created_day = datetime.utcnow().date().
I cannot save time_created_day to the db because of AttributeError: 'datetime.date' object has no attribute 'tzinfo'
How to fix this (add tzinfo)?
Ok, here is one way that I did this.
If you need to add tzinfo, you may use the below.
from datetime import datetime
import pytz
time_created_day = datetime.datetime.utcnow().date()
time_created_day_with_tz_info = datetime(time_created_day.year,
time_created_day.month, time_created_day.day, tzinfo=pytz.timezone('UTC'))
> print time_created_day_with_tz_info
> datetime.datetime(2018, 5, 9, 0, 0, tzinfo=<UTC>)
If I run the method
from datetime import datetime
from timedelta import time
def action_retbook(self, cr, uid, ids, context=None):
dt = datetime.date.now()
todaydate = datetime.strptime(dt, "%y/%m/%d")
x=6
cr.execute("""update rmkbook_issue set dt_of_return ='%s' where id= %s """ %(todaydate, x))
return
I get the error 'method_descriptor' object has no attribute 'now'. Why?
You can run the method now() like this:
dt = datetime.now()
You can check this question as well
I believe
from datetime import datetime
datetime.now()
Works.. in python 3.9.7