LoginSignup
4
3

More than 5 years have passed since last update.

日時 ⇔ 文字列

Last updated at Posted at 2012-12-26

time_struct から文字列にしたり、文字列から time_struct にします。

>>> import time
>>> now = time.localtime()
>>> now
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=0)

>>> str_now = time.strftime('%c', now)
>>> str_now
'05/08/12 04:03:42'
>>> time.strptime(str_now, '%c')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

>>> str_now = time.strftime('%Y/%m/%d %H:%M:%S', now)
>>> str_now
'2012/05/08 04:03:42'
>>> datetime.datetime.strptime(str_now, '%Y/%m/%d %H:%M:%S')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

time.strftime() および time.strptime() のフォーマット文字列はドキュメント の通り。C 言語と同じみたいです。

その他 time.asctime() で C 言語の asctime() と同じフォーマットにしてくれるみたいですが、この文字列を struct_time に変換する方法は用意されていないようです。

>>> asctime = time.asctime()
>>> asctime
'Tue May  8 04:03:42 2012'
>>> time.strptime(asctime, '%a %b %d %H:%M:%S %Y')
time.struct_time(tm_year=2012, tm_mon=5, tm_mday=8, tm_hour=4, tm_min=3, tm_sec=
42, tm_wday=1, tm_yday=129, tm_isdst=-1)

time と datetime の区別がついてないのですが、日付の加減算を行わない場合は time でいいような気がします。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3