Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Parsing and converting string into timestamp [closed]

I have string in next format: 2017-02-14T09:51:46.000-0600

What is the best approach to parse and convert string into timestamp? I have options to use regular expression or to write my own function for parsing, but are there any builtin methods which can help me?

like image 340
Shiva Rama Krishna Avatar asked Oct 23 '25 09:10

Shiva Rama Krishna


1 Answers

First part would be creating datetime object:

from datetime import datetime

date_string = "2017-02-14T09:51:46.000-0600"
# I'm using date_string[:-9] to skip ".000-0600"
format_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z'))

After which format date is:

print(format_date)
2017-02-14 09:51:46

And timestamp is:

print(format_date.timestamp())
1487062306.0

Little clarification here, on python reference page, you can see definition for '%Y-%m-%dT%H:%M:%S.%f%z') format specifiers I used.

  • %Y: Year with century as a decimal number, e.g. 1970, 1988, 2001, 2013
  • %m: Month as a zero-padded decimal number (e.g. 01, 02, ..., 12)
  • %d: Day of the month as a zero-padded decimal number (e.g. 01, 02, ..., 31)
  • %H: Hour (24-hour clock) as a zero-padded decimal number (e.g 00, 01, ..., 23)
  • %M: Minute as a zero-padded decimal number (e.g 00, 01, ..., 59)
  • %S: Second as a zero-padded decimal number (e.g. 00, 01, ..., 59)
  • %f: Microsecond as a decimal number, zero-padded on the left (000000, 000001, ..., 999999)
  • %z: UTC offset in the form +HHMM or -HHMM, empty string if the the object is naive, (empty or +0000, -0400, +1030)
like image 55
Aleksandar Makragić Avatar answered Oct 26 '25 05:10

Aleksandar Makragić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!