0
print str(now.month) + str(now.day) + str(now.year)

Result: 1162014

How do I further format the result to add slashes: 11/6/2014

Also how would I do formatting for hour, minute, and second? hh:mm:ss

Displaying datetime as month/day/year & hours:minutes:seconds:

import datetime
now = datetime.datetime.now()
print datetime.datetime.strftime(now, '%m/%d/%Y')
print datetime.datetime.strftime(now, '%H:%M:%S')

Displaying datetime as month/day/year & hours:minutes:seconds on one line:

import datetime
now = datetime.datetime.now()
print datetime.datetime.strftime(now, '%m/%d/%Y %H:%M:%S')

special thanks to senshin for the help

1
  • Make sure you check the case on your statement for printing the time - lowercase %m means "month", while uppercase %M means "minute". Commented Jan 16, 2014 at 19:49

2 Answers 2

3

Use datetime.strftime(). I assume you meant 1/16/2014, rather than 11/6/2014, given that today is the 16th of January.

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.datetime.strftime(now, '%m/%d/%Y')
'01/16/2014'
>>> datetime.datetime.strftime(now, '%H:%M:%S')
'14:18:16'
>>> datetime.datetime.strftime(now, '%I:%M:%S')
'02:18:16'

If for some reason you didn't want to use datetime.strftime(), you could instead do:

>>> print '/'.join(map(str, [now.month, now.day, now.year]))
'1/16/2014'
Sign up to request clarification or add additional context in comments.

6 Comments

@user3201139 No, you should also use datetime.strftime for formatting the time part of it! datetime.datetime.strftime(now, '%H:%M:%S'). Or, if you want twelve-hour time, use %I:%M:%S instead.
Thank you, ill give it a try right now. Whats the benefit of the first format versus the second format?
@user3201139 Maintainability, I guess. It's more concise to use datetime.strftime, and that's also considered the standard way of formatting dates in Python. It also gives you more flexibility if you want to change the time format later on.
How would I display them on the same line in the form: mm/dd/yyyy hh:mm:ss
@user3201139 You should read the strftime and strptime docs. For that format, you just put the date and time specifications together. %m/%d/%Y %H:%M:%S.
|
0

Time travel to 2025.

If you're using python 3.11 and 3.12, here's how to do it now:

from datetime import datetime
now = datetime.now()

print(now.year)
print(now.day)
print(now.strftime("%m/%d/%y"))
print(now.strftime("%H:%M:%S"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.