14

I am trying to use datetime objects, including datetime.month, datetime.day, and datetime.hour.

The problem is that these objects (say datetime.month) give values as 1, 2, 3, and so on to 12. Instead, I need these in the format 01,02,03 and so on to 12. There's a similar issue with days and months.

How can I switch to this format?


I realized this wasn't a very clear question:

I'm using string formatting to print values from a dictionary I have with timestamps.

So, the expression is roughly:

print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) )

My values were originally in the correct "%Y-%m-%d form (such as 2000-01-01). Using the above, I get 2000-1-1.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
ehertele
  • 221
  • 1
  • 3
  • 9
  • You'll find that `08` isn't a value in python. If you want to print them, use strftime, not the individual attributes. – Wooble Jul 24 '12 at 18:50
  • Values in Python don't contain a format. You need to specify the format when you print it out or convert it to a string. – Mark Ransom Jul 24 '12 at 18:55
  • @MarkRansom See above, if I'm using string formatting with these objects, they're defined (with month) to be 1 to 12 inclusive. – ehertele Jul 24 '12 at 19:05
  • @ehertele See my answer. The code you just posted won't even run, so it's a bit unclear exactly what you mean when you say "my values were originally in the correct form." What did you change that broke it? – Ricardo Altamirano Jul 24 '12 at 19:07
  • @RicardoAltamirano What I mean is that using string formatting with %s and the object datetime objects gives you singular values (like 1 to 12) as that's how they're defined. Naturally my code won't run, because it's not actual code. Thanks for the help though. – ehertele Jul 24 '12 at 19:20
  • When you converted the date string into a datetime, each portion was converted to a number. As I said, numbers don't have formats, so when you converted them back to strings with `%s` they automatically took on the most natural form which is a single digit for numbers less than 10. – Mark Ransom Jul 24 '12 at 19:21
  • @MarkRansom Ah, I understand now. All clear. Thanks – ehertele Jul 24 '12 at 19:26

4 Answers4

31

You can print the individual attributes using string formatting:

print ('%02d' % (mydate.month))

Or more recent string formatting (introduced in python 2.6):

print ('{0:02d}'.format(a.month))  # python 2.7+ -- '{:02d}' will work

Note that even:

print ('{0:%m}'.format(a))  # python 2.7+ -- '{:%m}' will work.

will work.

or alternatively using the strftime method of datetime objects:

print (mydate.strftime('%m'))

And just for the sake of completeness:

print (mydate.strftime('%Y-%m-%d')) 

will nicely replace the code in your edit.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • +1 for `strftime`, but in your first example, I thought `str.format` was preferred over the `%` operator? – Ricardo Altamirano Jul 24 '12 at 18:59
  • @RicardoAltamirano -- It is, I frequently use C still, so I still need to relearn `.format` everytime I want to use it. I've updated. – mgilson Jul 24 '12 at 19:01
  • No worries; I just wanted to make sure, since I always use `str.format` in place of `%`. I was about to add `strftime` to my answer, but since it's already nicely covered in yours, I just wanted to clarify that point and keep your answer as the primary one. – Ricardo Altamirano Jul 24 '12 at 19:03
  • 1
    @RicardoAltamirano -- and while reading the docs, I learned that `'{:%m}'.format(mydate)` will work too. Pretty neat. – mgilson Jul 24 '12 at 19:04
  • Using `%02d` instead of `&s` is exactly what I wanted. Thanks. (And sorry for being so unclear and not useful above....it's sackcloth and ashes for me) – ehertele Jul 24 '12 at 19:11
  • @ehertele I still suggest using `str.format` instead of the `%` operator, although either one will work. – Ricardo Altamirano Jul 24 '12 at 19:11
  • Would you be so kind as to provide a link to the docs where you discovered that datetime supports `format` formatting as such (I can't seem to locate it)? I'm sure I'll find a use for that going forward, so +1 from me. (Although I'm now wondering what else in the stdlib may have custom formatters...) – Jon Clements Jul 24 '12 at 19:24
  • @JonClements a link is here: ( http://docs.python.org/library/string.html#format-examples ) If you search the page for "Using type-specific formatting" you should be able to find it. It looks like using `__format__` is the way to do this sort of formatting on your own classes (naturally). – mgilson Jul 24 '12 at 19:30
  • Thanks for link. I have written my own formatters -- just wasn't aware that datetime had been geared to have conversion specifiers via format. – Jon Clements Jul 24 '12 at 19:55
2

zfill is easier to remember:

In [19]: str(dt.month).zfill(2)
Out[19]: '07'
Danil
  • 4,781
  • 1
  • 35
  • 50
1

You can convert them to strings and simply pad them:

import datetime

d = datetime.datetime(2012, 5, 25)

m = str(d.month).rjust(2, '0')
print(m) # Outputs "05"

Or you could just a str.format:

import datetime

d = datetime.datetime(2012, 5, 25)

print("{:0>2}".format(d.month))

EDIT: To answer the updated question, have you tried this?

import datetime
d = datetime.datetime(2012, 5, 25)
print("{:0>4}-{:0>2}-{:0>2}".format(d.year, d.month, d.day))

You said you were originally printing them using string formatting, so what did you change? This code:

print "%s-%s-%s"%(date.year, date.month, date.day, etc., len(str) )

Doesn't really make any sense, since I'm a little unclear as to what arguments you are passing in. I assume just date.year, date.month, and date.day, but it's unclear. What action are you performing with len(str)?

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
  • Seems like the hard way to go about it, but since it actually works you'll get a token +1 from me. – Mark Ransom Jul 24 '12 at 18:56
  • @MarkRansom True, it is a bit of the hard way, but since I noticed that `strftime` was already covered right before I posted, I figured I would cover what wasn't. – Ricardo Altamirano Jul 24 '12 at 19:08
0

Wiki: https://www.w3schools.com/python/python_datetime.asp

You can check the strftime() method. Look this out:

from datetime import datetime

today = datetime.today()

print(today.strftime("%Y%m%d"))  # yyyyMMdd