In Python 2.7 I want to print datetime objects using string formatted template. For some reason using left/right justify doesn't print the string correctly.
import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l) #print items in the list using template
This will result:
>25 >25
Instead of
2013-06-26 09:00:00 2013-06-26 09:00:00
Is there some trick to making datetime objects print using string format templates?
It seems to work when I force the datetime object into str()
print template.format(str(l[0]), str(l[1]))
but I'd rather not have to do that since I'm trying to print a list of values, some of which are not strings. The whole point of making a string template is to print the items in the list.
Am I missing something about string formatting or does this seem like a python bug to anyone?
SOLUTION
#mgilson pointed out the solution which I missed in the documentation. link
Two conversion flags are currently supported: '!s' which calls str()
on the value, and '!r' which calls repr().
Some examples:
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first
The problem here is that datetime objects have a __format__ method which is basically just an alias for datetime.strftime. When you do the formatting, the format function gets passed the string '>25' which, as you've seen, dt.strftime('>25') just returns '>25'.
The workaround here it to specify that the field should be formatted as a string explicitly using !s:
import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0!s:>25} {1!s:>25} "
out = template.format(*l)
print out
(tested on both python2.6 and 2.7).
datetime.datetime has format method. You need to convert it str.
>>> '{:%Y/%m/%d}'.format(dt)
'2013/06/26'
>>> '{:>20}'.format(dt)
'>20'
>>> '{:>20}'.format(str(dt))
' 2013-06-26 09:00:00'
>>> import datetime
>>> dt = datetime.datetime(2013, 6, 26, 9, 0)
>>> l = [dt, dt]
>>> template = "{0:>25} {1:>25}"
>>> print template.format(*l)
>25 >25
>>> print template.format(*map(str, l))
2013-06-26 09:00:00 2013-06-26 09:00:00
Try this:
print template.format(*map(str, l))
=> 2013-06-26 09:00:00 2013-06-26 09:00:00
It works by first converting the datetime objects to a string, which then can be formatted with the format method without problems.
Related
This question already has answers here:
What is the difference between __str__ and __repr__?
(28 answers)
Closed 5 months ago.
I'm trying to parse a string with the datetime standard library module and then display it.
When I try this code, the output looks correct:
>>> import datetime
>>> endDate = datetime.datetime.strptime("2022-05-03", '%Y-%m-%d').date()
>>> print(endDate)
2022-05-03
But it changes if the endDate is put into a list or tuple:
>>> print([endDate])
[datetime.date(2022, 5, 3)]
Why does the output have the "datetime.date" text?
>>> from datetime import datetime
>>> endDate = datetime.strptime("2022-05-03", '%Y-%m-%d').date()
When you printed the date object, it used str representation of the date object.
>>> str(endDate)
'2022-05-03'
When you included that in a container and printed it, the container internally uses repr representation of the object
>>> repr(endDate)
'datetime.date(2022, 5, 3)'
print function by default converts all the objects passed to it to a String with str.
All non-keyword arguments are converted to strings like str() does
To understand this better, we can create a class which implements both __str__ and __repr__ functions like this
>>> class Test:
... def __str__(self):
... return "TEST_FROM_STR"
...
... def __repr__(self):
... return "TEST_FROM_REPR"
...
Now, we can create instances of that class and print them separately and with list, like this
>>> Test()
TEST_FROM_REPR
>>> [Test()]
[TEST_FROM_REPR]
>>> print(Test())
TEST_FROM_STR
>>> print([Test()])
[TEST_FROM_REPR]
Hi I'm a newbie learning python and I want to print something only if current time starts with x (for example, if current time starts with = 4, print "hi", time = 4:18), this is the code I made, it says attribute error:
import datetime
local = datetime.datetime.now().time().replace(microsecond=0)
if local.startswith('16'):
print("Hi! It's ", local)
The .replace() method returns a date object. date objects don't have a .startswith() method. That method is only for str.
Try converting your date to a string first:
if str(local).startswith('16'):
print("Hi! It's ", local)
The documentation lists all of the methods available on a date object.
You need to first convert it to a string, as datetime objects have no startswith() method. Use strftime, example:
import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t2 = t.strftime('%m/%d/%Y')
will yield:
'02/23/2012'. Once it's converted, you can use t2.startswith().
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
You can get the hour of the time and check if it is 16:
if local.hour == 16:
print("Hi! It's ",local)
If you need to use startswith() then you can convert it to a string like this:
if str(local).startswith('16'):
print("Hi! It's ", local)
That's not a good way. Check the time as int is the better solution here.
replace() has 2 needed str arguments. You use a named attribute which doesn't exist.
I trying this in Python. What is the difference of those:
>>> a = datetime.fromtimestamp(1373576406)
>>> a.replace(tzinfo=tzutc())
datetime.datetime(2013, 7, 12, 0, 0, 6, tzinfo=tzutc())
>>> a.strftime('%s')
'1373576406'
and
>>> datetime.fromtimestamp(1373576406).replace(tzinfo=tzutc()).strftime('%s')
'1373580006'
I don't really understand why this is happening. Shouldn't both timestamps be equal?
I tried these in both Python 3.3.2 and Python 2.7.1
datetime.replace returns a new datetime instance.
In your first example you are ignoring the return value of datetime.replace and are then doing datetime.strftime on your old datetime instance.
This causes the inequality you are experiencing.
To make both examples equal you would have to edit the verbose one to look like:
>>> a = datetime.fromtimestamp(1373576406)
>>> a = a.replace(tzinfo=tzutc())
>>> a.strftime('%s')
'1373576406
I am having a weird problem.
I am running a django app and in one of my models I have a method to compare the time that the user gives and the time that is stored in the model db
So, for debugging purposes, I do this.
print self.start
print start
print self.start.time < start.time
And the output is:
2012-10-15 01:00:00+00:00
2012-10-22 01:01:00+00:00
False
HOW IS THIS POSSIBLE?!?!?!
I tried this in the django shell and in the python cli! Both give me True! With the same values.
Thanks guys.
.time is a method, not a property.
>>> import datetime
>>> a = datetime.datetime(2012, 10, 15, 1, 0, 0)
>>> a.time
<built-in method time of datetime.datetime object at 0x10049f508>
>>> a.time()
datetime.time(1, 0)
Therefore, the correct code would be if self.start.time() < start.time().
Is there a built-in function that converts a datetime.date object into a datetime.datetime object with 0's for the missing stuff? For example, suppose
tdate = datetime.date(2012,1,31)
I want to write something like either of these
tdatetime = datetime.date.datetime()
tdatetime = datetime.datetime(tdate)
and I want the output to be
datetime.datetime(2012, 1, 31, 0, 0)
But neither works. There is a builtin function to go from datetime.datetime to datetime.date, but I'm looking for the reverse operation.
One very poor solution would be to write:
datetime.datetime(tdate.year(), tdate.month(), tdate.day(), 0, 0)
I specifically want to avoid this bad way of doing it.
I've already written my own small function to do this, but I think it should be provided in the module. It's cluttering up some system-wide imports to use my function. It's workable, just not very Pythonic.
I'm just asking to see if anyone knows whether there is an efficient way to do it using only datetime module functions.
Use .combine(date, time) with an empty time instance:
>>> import datetime
>>> tdate = datetime.date(2012,1,31)
>>> datetime.datetime.combine(tdate, datetime.time())
datetime.datetime(2012, 1, 31, 0, 0)
If you like to use a constant instead, use time.min:
>>> datetime.datetime.combine(tdate, datetime.time.min)
datetime.datetime(2012, 1, 31, 0, 0)