I am wanting to pass the current time as an object into a strftime reference. If I use:
d = date.fromtimestamp(time.time())
print d.strftime("%d-%b-%Y %H:%M:%S")
This will print out the time, but not include the minutes/hours etc:
04-Jul-2014 00:00:00
If I try use a different call to try and get the minutes/hours:
d = date.fromtimestamp(time.localtime())
I get:
TypeError: a float is required
Both time.time() and time.localtime() appears to actually contain seconds/minutes etc, but not display them. Thoughts? gmtime also returns "AttributeError: 'time.struct_time' object has no attribute 'strftime'".
You should use
from datetime import datetime
not
from datetime import date
eg.
import time
from datetime import datetime
d = datetime.fromtimestamp(time.time())
print d.strftime("%d-%b-%Y %H:%M:%S")
use datetime.fromtimestamp(time.time()) since date.fromtimestamp(time.time()) only draws date
d = datetime.fromtimestamp(time.time())
print d
print d.strftime("%d-%b-%Y %H:%M:%S")
#output 04-Jul-2014 11:32:40
Related
Consider this:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
'{0.strftime("%p")}'.format(now)
# gives
# AttributeError: 'datetime.datetime' object has no attribute 'strftime("%p")'
This seems to imply that I can't call a class method inside the format (I guess that's what strftime is).
What's a workaround for this (assuming I need to call the method inside the string, and keep using a format) ?
You could do this.
>>> from datetime import datetime
>>> now = datetime.now()
>>> '{0:%p}'.format(now)
'PM'
This will also work with f-strings.
>>> f"{now:%p}"
'PM'
You can use the f-string:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
print(f'{now.strftime("%p")}')
Else:
from datetime import datetime
now = datetime.now()
now.strftime("%p") # returns 'PM'
'{0.day}'.format(now) # returns 22
print('{0:%p}'.format(now))
Documentation
strftime() and strptime() Behavior
You could use f-strings like this:
from datetime import datetime
now = datetime.now()
now.strftime("%p")
print(f'{now.day}')
print(f'{now.strftime("%p")}')
In python, I have a datetime object in python with that format.
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
In other classes, I'm using this object. When i reach this object,i want to extract time from it and compare string time.
Like below;
if "01:15:13" == time_from_datetime_object
How can I do this?
You need to use the strftime method:
from datetime import datetime
date_time_str = '2021-01-15 01:15:13'
datetime_object = datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S')
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
print("match")
If you want to compare it as string:
if "01:15:13" == datetime_object.strftime('%H:%M:%S'):
Use its time method to return a time object, which you can compare to another time object.
from datetime import time
if datetime_object.time() == time(1, 15, 13):
...
You may have to be careful with microseconds though, so at some point you might want to do datetime_object = datetime_object.replace(microsecond=0), should your datetime objects contain non-zero microseconds.
How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04
I'd like to get the time before X seconds before
datetime.time.now(). For example, if the time.now() is 12:59:00, and I minus 59, I want to get 12:00:00.
How can I do that?
You can use time delta like this:
import datetime
print datetime.datetime.now() - datetime.timedelta(minutes=59)
import datetime
datetime.datetime.now() - datetime.timedelta(seconds=59)
Should do the trick
You can read more about timedelta on the documentation:
class datetime.timedelta
A duration expressing the difference between
two date, time, or datetime instances to microsecond resolution.
You need to use timedelta
from datetime import timedelta, datetime
d = datetime.now()
d = d - timedelta(minutes=59)
print d
You can try dateutil:
datetime.datetime.now() + dateutil.relativedelta.relativedelta(second=-60)
In my code I ask the user for a date in the format dd/mm/yyyy.
currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ")
day,month,year = currentdate.split('/')
today = datetime.date(int(year),int(month),int(day))
This returns the error
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
if I remove the int() then I end up with the same error only it says it received a 'str'
What am I doing wrong?
It seems that you have imported datetime.datetime module instead of datetime. This should work though:
import datetime
currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ")
day,month,year = currentdate.split('/')
today = datetime.date(int(year),int(month),int(day))
..or this:
from datetime import date
currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ")
day,month,year = currentdate.split('/')
today = date(int(year),int(month),int(day))
Do you import like this?
from datetime import datetime
Then you must change it to look like this:
import datetime
Explanation: In the first case you are effectively calling datetime.datetime.date(), a method on the object datetime in the module datetime. In the later case you create a new date() object with the constructor datetime.date().
Alternatively, you can change the import to:
from datetime import datetime, date
and then construct with date(y,m,d) (without the datetime. prefix).
if you already have
from datetime import datetime
then you can construct like so:
christmas = datetime(2013,12,25)
You can use both datetime and datetime.datetime.
Write the imports like this:
from datetime import datetime
import datetime as dt
time_1 = datetime.strptime('17:00:00', '%H:%M:%S')
time_1 = dt.time(time_1.hour, time_1.minute, time_1.second)
I can reproduce the error if I do
from datetime import *
It goes away when I do
import datetime
So check your imports.
I suspect that the datetime reference the object and not the module. You probably did have the following code (probably more complex):
from datetime import datetime
currentdate = raw_input("Please enter todays date in the format dd/mm/yyyy: ")
day,month,year = currentdate.split('/')
today = datetime.date(int(year),int(month),int(day))
You are thus calling the date method of the datetime class instead of calling the date function of the datetime module.
You can print the datetime object to see if this is really the case:
>>> import datetime
>>> print datetime
<module 'datetime' (built-in)>
>>> print datetime.date(1, 1, 1)
0001-01-01
>>> datetime = datetime.datetime
>>> print datetime
<type 'datetime.datetime'>
>>> print datetime.date(1, 1, 1)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print datetime.date(1, 1, 1)
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int'
This is because you have used variables like year, month, day.
Use something like this:
year1, month1, day1 = [int(d) for d in startDate.split('-')]
print(date(year1, month1, day1))
and it will work.
The error suggest's your import looks fine. Instead, while doing an operation using datetime, make sure the values are converted to datetime format first.
use pandas.to_datetime to do the same, before you use any operation on the same.