[PYTHON] I tried to convert datetime <-> string with tzinfo using strftime () and strptime ()

environment

Python 2.7.10

Reference material

8.1. datetime — basic date and time types

Use strftime to get the datetime string holding tzinfo

>>> from datetime import datetime
>>> import pytz
>>> 
>>> jst = pytz.timezone('Japan')
>>> jst_datetime = datetime.now().replace(tzinfo=jst)
>>> print jst_datetime
2015-11-12 16:09:18.544266+09:00
>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %z')
>>> print jst_datetime_str
2015-11-12 16:09:18 +0900
>>> datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %Z')
'2015-11-12 16:09:18 JST'

It is possible to output a datetime character string with tzinfo.

Get datetime with tzinfo from datetime string using strptime

>>> print jst_datetime_str
2015-11-12 16:09:18 +0900
>>> datetime.strptime(jst_datetime_str, '%Y-%m-%d %H:%M:%S %z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/lib/python2.7/_strptime.py", line 317, in _strptime
    (bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
>>> 

I tried to get the datetime with timsezone using the datetime string with tzinfo, but I got an error.

ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'

I get an error that the'% z'specifier is in a bad format.

The result of various investigations http://stackoverflow.com/questions/2609259/converting-string-to-datetime-object-in-python

It seems that% z is not supported in python2.7. It seems to work with python3.2. I can't change the version, so try another method

>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S %Z')
>>> print jst_datetime_str
2015-11-12 16:09:18 JST
>>> datetime.strptime(jst_datetime_str, '%Y-%m-%d %H:%M:%S %Z')
datetime.datetime(2015, 11, 12, 16, 9, 18)

I tried using% Z, but this time I get a datetime without tzinfo, although no error occurs.

Looking for others http://nekoya.github.io/blog/2013/06/21/python-datetime/

This person also couldn't use% Z, so it seems that he used "replace (tzinfo = pytz.utc)" to set it. It seems impossible to convert using a specifier, so I tried to handle it by pushing

>>> from datetime import datetime
>>> import pytz
>>> 
>>> jst = pytz.timezone('Japan')
>>> jst_datetime = datetime.now().replace(tzinfo=jst)
>>> print jst_datetime
2015-11-12 16:54:19.564920+09:00
>>> jst_datetime_str = datetime.strftime(jst_datetime, '%Y-%m-%d %H:%M:%S') + ' ' + jst_datetime.tzinfo.zone
>>> print jst_datetime_str
2015-11-12 16:54:19 Japan
>>> zone = jst_datetime_str.split(' ')[-1]
>>> print zone
Japan
>>> datetime_str = ' '.join(jst_datetime_str.split(' ')[:2])
>>> print datetime_str
2015-11-12 16:54:19
>>> datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(zone))
datetime.datetime(2015, 11, 12, 16, 54, 19, tzinfo=<DstTzInfo 'Japan' JST+9:00:00 STD>)

Like this.

Summary

-In python2.7, the specifiers'% Z'and'% z'cannot be used in strptime. ・ However, it can be used normally with strftime. ・ I haven't confirmed it later, but it seems that python3.2 can be used with strptime. ・ Honestly, it feels like a force, but I wonder if there is any other good way.

Recommended Posts

I tried to convert datetime <-> string with tzinfo using strftime () and strptime ()
Python datetime How to calculate dates and convert strings strftime, strptime [Definitive Edition]
I tried to read and save automatically with VOICEROID2 2
I tried to implement and learn DCGAN with PyTorch
I tried to automatically read and save with VOICEROID2
I tried to implement Grad-CAM with keras and tensorflow
[Python] Convert time display (str type) using "" "and"'" to seconds (float type) with datetime and timedelta
I tried to predict and submit Titanic survivors with Kaggle
I tried to get Web information using "Requests" and "lxml"
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried to visualize bookmarks flying to Slack with Doc2Vec and PCA
I tried to make a periodical process with Selenium and Python
I tried using PyEZ and JSNAPy. Part 4: Automate ISP setup with PyEZ and JSNAPy
I tried to create Bulls and Cows with a shell program
I tried to make a todo application using bottle with python
I tried to easily detect facial landmarks with python and dlib
I tried using Amazon SQS with django-celery
I tried using Azure Speech to Text.
I tried using Twitter api and Line api
I tried to implement Autoencoder with TensorFlow
I tried to visualize AutoEncoder with TensorFlow
I tried to get started with Hy
I tried using Selenium with Headless chrome
I tried using PyEZ and JSNAPy. Part 2: I tried using PyEZ
I tried to implement CVAE with PyTorch
I tried to solve TSP with QAOA
I tried to predict Covid-19 using Darts
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I tried to express sadness and joy with the stable marriage problem.
Mayungo's Python Learning Episode 6: I tried to convert a character string to a number
I tried to learn the angle from sin and cos with chainer
I tried to extract and illustrate the stage of the story using COTOHA
I tried to create a sample to access Salesforce using Python and Bottle
I tried updating Google Calendar with CSV appointments using Python and Google APIs
I tried to control the network bandwidth and delay with the tc command
I tried to predict next year with AI
I tried to notify the update of "Hamelin" using "Beautiful Soup" and "IFTTT"
I tried using PyEZ and JSNAPy. Part 1: Overview
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to detect Mario with pytorch + yolov3
I tried to implement reading Dataset with PyTorch
I tried to use lightGBM, xgboost with Boruta
I tried web scraping using python and selenium
I tried to learn logical operations with TF Learn
I tried to move GAN (mnist) with keras
I tried object detection using Python and OpenCV
I tried to save the data with discord
I tried to use Java with Termux using Termux Arch but it didn't work
I tried to detect motion quickly with OpenCV
I tried to integrate with Keras in TFv1.1
I tried to synthesize WAV files using Pydub.
I tried using the Python library "pykakasi" that can convert kanji to romaji.
I tried to automate internal operations with Docker, Python and Twitter API + bonus
Python programming: I tried to get (crawling) news articles using Selenium and BeautifulSoup4.
I tried playing with PartiQL and MongoDB connected
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried using mecab with python2.7, ruby2.3, php7
I tried function synthesis and curry with python
Three things I was addicted to when using Python and MySQL with Docker