LoginSignup
11
6

More than 5 years have passed since last update.

Python / datetime > YYYYMMDD形式をYYYY/MM/DDに変換する実装

Last updated at Posted at 2017-03-24
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
Python 3.6.0 on virtualenv

20170324という文字列を2017/03/24という文字列に変換したい。

test_python_170324k.py
orgstr = "20170324"  # YYYYMMDD
print(orgstr)

# 1
newstr = orgstr[:4] + '/' + orgstr[4:6] + '/' + orgstr[6:]
print(newstr)

# 2
from datetime import datetime as dt
adt = dt.strptime(orgstr, '%Y%m%d')
newstr = adt.strftime('%Y/%m/%d')
print(newstr)
結果
$ python test_python_170324k.py 
20170324
2017/03/24
2017/03/24

最初はinsertなど考えていたが、
http://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python
によると

answered Oct 26 '10 at 12:02
bgporter
An important point that often bites new Python programmers but the other posters haven't made explicit is that strings in Python are immutable -- you can't ever modify them in place

とのこと。

11
6
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
11
6