Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime to string without microsecond component

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).

What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?

>>> import datetime >>> print unicode(datetime.datetime.now()) 2011-11-03 11:13:39.278026 

I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.

Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.

like image 581
davidchambers Avatar asked Nov 03 '11 18:11

davidchambers


People also ask

How do you get the current time without seconds in Python?

Try print(f"{now. hour}:{now. minute}") . Note that this will not add leading zeros or other useful time formatting, but that can be added trivially by referencing the documentation for formatting strings.

Is datetime now a string?

The program below converts a datetime object containing current date and time to different string formats. Here, year , day , time and date_time are strings, whereas now is a datetime object.

Is timestamp in seconds or milliseconds in Python?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time. time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.


2 Answers

If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:

>>> import datetime >>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") '2011-11-03 18:21:26' 

See the documentation of datetime.strftime() for an explanation of the % directives.

like image 179
Sven Marnach Avatar answered Oct 12 '22 14:10

Sven Marnach


>>> import datetime >>> now = datetime.datetime.now() >>> print unicode(now.replace(microsecond=0)) 2011-11-03 11:19:07 
like image 34
davidchambers Avatar answered Oct 12 '22 14:10

davidchambers