Python Datetime to String Without Microsecond Component

Python datetime to string without microsecond component

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.

Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:

datetime.datetime.now().isoformat(sep=" ", timespec="seconds")

Is there a way i can use datetime to convert a string to milliseconds without using timedelta?

Since timestamps are relative to the Unix Epoch (1970-01-01) you can make a datetime object from your time by prepending that date to it and then getting the timestamp of the resultant object to get the time string converted to seconds . Since python timestamps are floating point representations of seconds since the epoch, you will need to multiply by 1000 and convert to integer to get the number of milliseconds:

from datetime import datetime

t = "00:05:52.654321"
d = datetime.strptime('1970-01-01 ' + t, '%Y-%m-%d %H:%M:%S.%f')
print(int(d.timestamp()*1000))

Output:

352654

If you actually want microseconds, multiply by 1000000 instead.

As an alternative, you can split the time string on : and sum the parts, multiplying by 60 or 3600 to convert the hour and minute parts to seconds:

t = "00:05:52.654321"

millisecs = int(sum([float(v) * 1000 * 60 ** (2 - i) for i, v in enumerate(t.split(':'))]))
print(millisecs)

Output:

352654

Again, if you want microseconds, just multiply by 1000000 instead of 1000.

Print datetime in ISO format without milliseconds

You can replace the microseconds with 0 and use isoformat:

import pytz
from datetime import datetime
tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt).replace(microsecond=0)
print loc_dt.isoformat()
2015-09-17T19:12:33+08:00

If you want to keep loc_dt as is do the replacing when you output:

loc_dt = tz.localize(dt)
print loc_dt.replace(microsecond=0).isoformat()

As commented you would be better passing the tz to datetime.now:

 dt = datetime.now(tz)

The reasons are discussed in pep-0495, you might also want to add an assert to catch any bugs when doing the replace:

 ssert loc_dt.resolution >= timedelta(microsecond=0)

Format a datetime into a string with milliseconds

To get a date string with milliseconds, use [:-3] to trim the last three digits of %f (microseconds):

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
'2022-09-24 10:18:32.926'

Or slightly shorter:

>>> from datetime import datetime
>>> datetime.utcnow().strftime('%F %T.%f')[:-3]

python datetime to string to plug into linear regression equation

strptime is a function that converts a string into a datetime object, you have a datetime object already, and you are trying to convert it to a string and back to a datetime object, this is not needed.

My guess is that you are trying to remove the time component of the datetime object in order to get the ordinal of the date, you can more easily do it this way:

now.date().toordinal()

But since toordinal() disregards the time component anyway doing the following will yield the same result:

now.toordinal()

simple way to drop milliseconds from python datetime.datetime object

You can use datetime.replace() method -

>>> d = datetime.datetime.today().replace(microsecond=0)
>>> d
datetime.datetime(2015, 7, 18, 9, 50, 20)

What's the correct datetime format for this string date generated by python?

As per comment:

from datetime import datetime
print(datetime.strptime('2022-08-30T11:53:52.204219', "%Y-%m-%dT%H:%M:%S.%f"))

Result:

2022-08-30 11:53:52.204219

Python datetime compare two time stamps without taking date into account

With exactly the code you have written, you're actually just going to be comparing two strings to one another since neither of them has been parsed as a datetime object.

Is there a specific reason that you explicitly do not want the date? If this is purely for comparison purposes, then the following should work since it will parse both times as being from the same date:

from datetime import datetime

time1 = datetime.strptime("16:00", "%H:%M")
time2 = datetime.strptime("17:00", "%H:%M")
print(time1)
print(time2)

Running this code prints:

1900-01-01 16:00:00
1900-01-01 17:00:00

and the underlying datetime objects can now be compared as you wanted.

Float to datetime returns wrong output (Same Month) - Python

I assumed df['tweet_creation'].loc[1] will return a number like the examples you gave.

Unfortunately, I don't know what f is, but I assumed it was a float.

My answer is inspired by this other answer: Converting unix timestamp string to readable date. You have a UNIX timestamp, so the easiest way is to use it and not convert it as a string.

from datetime import datetime, timedelta

dtobj = datetime.utcfromtimestamp(int(df['tweet_creation'].loc[1])) + timedelta(days=f-int(f))

To have the string representation you can use the function strftime.

datetime timestamp using Python with microsecond level accuracy

That's almost as good as it gets, since the C module, if available, overrides all classes defined in the pure Python implementation of the datetime module with the fast C implementation, and there are no hooks.

Reference: python/cpython@cf86e36

Note that:

  1. There's an intrinsic sub-microsecond error in the accuracy equal to the time it takes between obtaining the system time in datetime.now() and obtaining the performance counter time.
  2. There's a sub-microsecond performance cost to add a datetime and a timedelta.

Depending on your specific use case if calling multiple times, that may or may not matter.

A slight improvement would be:

INITIAL_TIMESTAMP: Final[float] = time.time()
INITIAL_TIMESTAMP_PERF_COUNTER: Final[float] = time.perf_counter()

def get_timestamp_float() -> float:
dt_sec = time.perf_counter() - INITIAL_TIMESTAMP_PERF_COUNTER
return INITIAL_TIMESTAMP + dt_sec

def get_timestamp_now() -> datetime:
dt_sec = time.perf_counter() - INITIAL_TIMESTAMP_PERF_COUNTER
return datetime.fromtimestamp(INITIAL_TIMESTAMP + dt_sec)


Anecdotal numbers

Windows:

# Intrinsic error
timeit.timeit('datetime.now()', setup='from datetime import datetime')/1000000 # 0.31 μs
timeit.timeit('time.time()', setup='import time')/1000000 # 0.07 μs

# Performance cost
setup = 'from datetime import datetime, timedelta; import time'
timeit.timeit('datetime.now() + timedelta(1.000001)', setup=setup)/1000000 # 0.79 μs
timeit.timeit('datetime.fromtimestamp(time.time() + 1.000001)', setup=setup)/1000000 # 0.44 μs
# Resolution
min get_timestamp_float() delta: 239 ns

Windows and macOS:






























































WindowsmacOS
# Intrinsic error
timeit.timeit('datetime.now()', setup='from datetime import datetime')/10000000.31 μs0.61 μs
timeit.timeit('time.time()', setup='import time')/10000000.07 μs0.08 μs
# Performance cost
setup = 'from datetime import datetime, timedelta; import time'--
timeit.timeit('datetime.now() + timedelta(1.000001)', setup=setup)/10000000.79 μs1.26 μs
timeit.timeit('datetime.fromtimestamp(time.time() + 1.000001)', setup=setup)/10000000.44 μs0.69 μs
# Resolution
min time() delta (benchmark)x ms716 ns
min get_timestamp_float() delta239 ns239 ns



Related Topics



Leave a reply



Submit