side7python 日付フォーマット ISO 8601形式でミリ秒で返す

in side7python •  4 years ago  (edited)
import pytz
import datetime

def time_format(dt):
    return "%s:%.3f%sZ" % (
        dt.strftime('%Y-%m-%dT%H:%M'),
        float("%.3f" % (dt.second + dt.microsecond / 1e6)),
        dt.strftime('%z')
    )   

time_format(datetime.datetime.now())


pytz使わないやり方

def time_format(dt):
    if dt.microsecond % 1000 >= 500:  # check if there will be rounding up
        dt = dt + datetime.timedelta(milliseconds=1)  # manually round up
    return dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] + 'Z'
Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!