4

I try to parse string to time-stamp with timezone format.

here is an example

"2016-02-18 16:13:07+09"

i want to know parsing this string format to time-stamp format in python.

how can i do that?

8
  • yes, but i dont know how can i try this T.T Commented Feb 23, 2016 at 8:32
  • Try writing a simple script that parses something much simpler than what you want to parse, using time.strptime, something like "2016-02-18" Commented Feb 23, 2016 at 8:35
  • hmm... just that's all? i need more efficient method Commented Feb 23, 2016 at 8:46
  • Please include a code example of your trial and error in your question. Commented Feb 23, 2016 at 8:49
  • Just that's all. what is this situation, i have to get the timestamp with timezone data from database, then i need insert another database. but when i bring that timestamp from first database, timestamp format is transformed to string format. So i need parse this string type to timestamp with timezone format Commented Feb 23, 2016 at 8:53

3 Answers 3

7

Is the UTC offset format in your string +09 or +0900 ?

If the offset in your string is 0900 you can use the below .If your UTC offset is only +09 as you mentioned in your question , you can pad the string with 00 and get the below code to work .

Code:

import datetime  
time="2016-02-18 16:13:07+0900"  
new_time=datetime.datetime.strptime(time,"%Y-%m-%d %H:%M:%S%z")  
print(new_time)  
new_time_python=datetime.datetime.strftime(new_time,"%m-%d-%y")  
print(new_time_python)  

Output

2016-02-18 16:13:07+09:00  
02-18-16 
Sign up to request clarification or add additional context in comments.

Comments

1

dateutil might be a suitable library for your purposes:

from dateutil.parser import parser

p = parser()
d = p.parse('2016-02-18 16:13:07+09'.decode('utf-8'))  # must be unicode string
d
>>> datetime.datetime(2016, 2, 18, 16, 13, 7, tzinfo=tzoffset(None, 32400))

Comments

0

If the UTC offset may be specified both as +HH and +HHMM format then you could use str.ljust() method to normalize the input time string. Then you could use .strptime() to parse it:

#!/usr/bin/env python3
from datetime import datetime

time_string = "2016-02-18 16:13:07+09"
dt = datetime.strptime(time_string.ljust(24, "0"), "%Y-%m-%d %H:%M:%S%z")
# ->  datetime.datetime(2016, 2, 18, 16, 13, 7, 
#                       tzinfo=datetime.timezone(datetime.timedelta(0, 32400)))

If your Python version doesn't support %z, see How to parse dates with -0400 timezone string in python?

2 Comments

working on python 3.8 but you have to use a 4 digit offset: (+0900 instead of +09)
@marcosbdm: the code works as is ideone.com/1gHBBd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.