0

How can I change my code to new output?

My code:

import datetime
x = datetime.datetime.today()
print(x) 
# Old Output: 2021-12-15 12:03:16.151803 

but I want to create new output (remove the 803 from 12:03:16.151803 and save whole new output 2021-12-15 12:03:16.151)

# New Output: 2021-12-15 12:03:16.151
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

The simplest way to do that is by slicing it

Example:

x = datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
print(x)
SirLez
  • 26
  • 4
0

You can use .replace method of datetime objects.

from datetime import datetime

now = datetime.now()
print(now)
# 2021-12-15 13:51:27.148999

modified = now.replace(microsecond=0)
print(modified)
# 2021-12-15 13:51:27

You just can not edit any value of a datetime object. .replace() method creates a new datetime objects having the modification you wanted.

nejdetckenobi
  • 564
  • 2
  • 8
  • 24