How to coverter string for timestamp object?

Asked

Viewed 164 times

1

How can I transform a string containing a date, example: 'Thu Jul 27 13:54:22 2017', in a datetime object, or time?

2 answers

0

def execute01():
    ''' Converte string para objeto time'''
    import time
    str_date = 'Thu Jul 27 13:54:22 2017'
    obj_date = time.strptime(str_date, "%a %b %d %H:%M:%S %Y")

    return time.strftime('%Y/%m/%d', obj_date)

def execute02():
    ''' Converte string para objeto datetime'''
    import datetime
    str_date = 'Thu Jul 27 13:54:22 2017'
    return datetime.datetime.strptime(str_date, "%a %b %d %H:%M:%S %Y").strftime("%Y/%m/%d")

def execute03():
    ''' Converte string para objeto arrow'''
    import arrow
    str_date = 'Thu Jul 27 13:54:22 2017'
    return arrow.get(str_date, 'ddd MMM DD HH:mm:ss YYYY').format('YYYY/MM/DD')

Running on the https://repl.it/JoBD/0

  • What are you trying to do? This is the correct answer to your question?

  • @Francisco the site allows the user to ask and answer at the same time. No problems.

  • But I think I could improve the explanation.

  • 1

    @Wallacemaxters I know that, but I don’t know if that’s what he was trying to do, I figured he wanted to show the current code in the question.

  • I accept all improvements!!!! D

  • @britodfbr just confirm us, your intention really was to publish the answer to your question, right?

  • @Wallacemaxters, yes. This is the answer I got. In transforming a string into a timestamp object. I accept any suggestion to improve.

  • Suggestion offered, simpler, leaner, more "friendly". :-)

  • @Thank you very much!!! implemented the suggestion. : D

Show 4 more comments

0

Arrow

pip install arrow

import datetime
timestamp = time.localtime()
str_time = arrow.get(timestamp).format('DD-MM-YYYY HH:mm:ss ZZ')
print (str_time)

Exit:

'27-07-2017 15:39:20 +00:00'

Editing:
Missing String to TS Conversion.

ts = arrow.get('27-07-2017 15:39:20', 'DD-MM-YYYY HH:mm:ss')
print (ts)

Exit:

2017-07-27T15:39:20+00:00  

See working on repl.it.*

* Remembering that repl.it localtime is different from ours.

  • and when timestamp is default type Thu Jul 27 13:54:22 2017?

  • Look at the documentation, just change the format, see Humanize, have even more options.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.