Hulk
Hulk

Reputation: 34180

Python date formatting without space?

How to display the following without any space also could we substitute a separator instead of space?

> log_time=datetime.datetime.now()
> print log_time
2009-12-16 16:10:03.558991

Upvotes: 11

Views: 25510

Answers (3)

Mithun Arunan
Mithun Arunan

Reputation: 932

This works like a charm!

Using T as separator

This conforms to the ISO standard for datetime representation. It should be readable by other libraries/software.

import datetime
datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.f%z")

Example: 2024-07-11T09:31:30.123456+0000

Without any separator

import datetime
datetime.datetime.now().strftime("%Y%m%d%H%M%S")

Using - as separator

import datetime
datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")

Using _ as separator

import datetime
datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")

Upvotes: 37

Bryan Laygond
Bryan Laygond

Reputation: 111

Use regular expression

import datetime
import re

print( re.sub("\D", "", str(datetime.datetime.now())) )

or use the join method

print( ''.join(i for i in str(datetime.datetime.now()) if i.isdigit()) )

Upvotes: 0

unwind
unwind

Reputation: 399949

Use datetime.date.strftime().

Upvotes: 3

Related Questions