-2

In python, I want to find the date and time and put it inside of a string.

I have tried this:

example = datetime.datetime.now()

print(example)

However it returns the date with the miliseconds. What do I do if i don't want the miliseconds included. Just the date and time formatted like this:

YYYY-MM-DD 00:00:00

Ali Syed
  • 23
  • 4

4 Answers4

0

You need to format the datetime output using this:

datetime.datetime.now().strftime('%H:%M:%S')

This will give you Hours:Minutes:Seconds

To get the format as per your requirements use:

datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

This will give you date time in YYYY-MM-DD 00:00:00 format without milliseconds.

My output: 2019-11-04 22:09:06

To see more directives: Link

Link says:

You can get the formatted date and time using strftime function. It accepts a format string that you can use to get your desired output

slamarseillebg
  • 306
  • 2
  • 6
0

If I understand your question corretly, somethinig like this should work for you.

from datetime import datetime
now = datetime.now()
date = now.strftime("%m/%d/%Y")
print("date:",date)

It came from here. There are other formatting examples in that post.

Tom B.
  • 55
  • 2
  • 7
0

Datetime's strftime functionality does exactly what you're looking for.

There is some overview and explanation here:

https://www.programiz.com/python-programming/datetime/strftime

print(example.strftime('%Y-%m-%d %H:%M:%S')) will give you the right answer.

I would also look at the arrow library, as it offers a nice API to work with time.

0

Try this:

import datetime
example = datetime.datetime.now()
print(example.strftime("%Y-%d-%m %H:%M:%S"))
Umesh Jadhav
  • 327
  • 1
  • 7