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.
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.
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.
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.
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.
>>> import datetime >>> now = datetime.datetime.now() >>> print unicode(now.replace(microsecond=0)) 2011-11-03 11:19:07
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With