Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kemsakurai/4de1e8fab59015cdb15bd8d91417475f to your computer and use it in GitHub Desktop.
Save kemsakurai/4de1e8fab59015cdb15bd8d91417475f to your computer and use it in GitHub Desktop.
Python datetime のミリ秒を変更する.m

Python で datatime の ミリ秒を変更したかったため以下のようなコードを実装した。

for elem in GistEntryPage.objects.all():
    if elem.first_published_at.microsecond == 0:
        elem.first_published_at.microsecond = 1
        elem.save()

以下のエラーとなった。

    AttributeError: attribute 'microsecond' of 'datetime.datetime' objects is not writable

datetime には、replace というメソッドが存在し、変更時には以下のように使用する。

for elem in GistEntryPage.objects.all():
    if elem.first_published_at.microsecond == 0:
        elem.first_published_at = elem.first_published_at.replace(microsecond = 1)
        elem.save()

これで、ミリ秒を書き換えることができた。


参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment