Skip to content

Instantly share code, notes, and snippets.

@kkAyataka
Last active June 14, 2022 16:13
Show Gist options
  • Save kkAyataka/bc12e99f850437b8480c to your computer and use it in GitHub Desktop.
Save kkAyataka/bc12e99f850437b8480c to your computer and use it in GitHub Desktop.
Python datetime to iso format string and iso format string to datetime
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""datetimeとISO 8601文字列の変換"""
import datetime
# datetimeからISO 8601を得る
d = datetime.datetime(2014, 11, 11, 9)
print d.isoformat() # 2014-11-11T09:00:00
# タイムゾーンが必要な場合はtzinfoを指定する
class JST(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=+9)
def dst(self, dt):
return datetime.timedelta()
d = datetime.datetime(2014, 11, 11, 9, tzinfo=JST())
print d.isoformat() # 2014-11-11T09:00:00+09:00
# ISO 8601文字列からdatetimeを得る
# タイムゾーンは処理できないので無視
d = datetime.datetime.strptime('2014-11-11T09:00:00+09:00'[:-6], '%Y-%m-%dT%H:%M:%S')
## タイムゾーンを(適当に)処理
isostr = '2014-11-11T09:00:00+09:00'
if isostr[-1:] == 'Z':
d = datetime.datetime.strptime(isostr[:-1], '%Y-%m-%dT%H:%M:%S')
elif isostr[-6:-5] == '+' or isostr[-6:-5] == '-':
sign = isostr[-6:-5]
hours = int(isostr[-5:].split(':')[0])
minutes = int(isostr[-5:].split(':')[1])
offsetmin = hours * 60 + minutes
if sign == '-':
offsetmin *= -1
utcoffset = datetime.timedelta(minutes=offsetmin)
d = datetime.datetime.strptime(isostr[:-6], '%Y-%m-%dT%H:%M:%S')
d -= utcoffset
#d = d.replace(tzinfo=UTC()) # UTCをセットしてもよさげ
print d.isoformat() # 2014-11-11T00:00:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment