Home > Blockchain >  How to convert str time to timestamp?
How to convert str time to timestamp?

Time:10-31

I have a string "15:15:00" I need to convert it to timestamp like 1410748201

Python

CodePudding user response:

A UNIX timestamp always needs a relation between a date and a time to actually form it, since it is the number of seconds that are passed since 1970-01-01 00:00. Therefore I would recommend you to use the datetime module.

Let's assume you have given the following format: "2022-10-31 15:15:00". With datetime you can convert the string into a datetime object by using the strptime() function. Afterwards, a datetime object gives you the ability to convert your datetime into a UNIX timestamp with the timestamp() method of your datetime object.

from datetime import datetime

datetime_str = "2022-10-31 15:15:00"
datetime_obj = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
print(datetime_obj.timestamp())
  • Related