Small Atom
Small Atom

Reputation: 164

Convert string date to unix time

I have problem to convert string of data to unix time

my script:

import datetime


s="2018-06-29 08:15:27"

date_time_obj = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

print(type(date_time_obj))

datetime.timestamp(date_time_obj)

and I have this error:

AttributeError: module 'datetime' has no attribute 'timestamp'

Upvotes: 1

Views: 1766

Answers (4)

Ramy M. Mousa
Ramy M. Mousa

Reputation: 5943

Try this:

from datetime import datetime  # pep8 import style

s = "2018-06-29 08:15:27"
unix_stamp = datetime.timestamp(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))

Output

1530252927.0

Another answer mentioned using .timestamp in date object.

Upvotes: 1

berlin
berlin

Reputation: 526

datetime.datetime.timestamp(date_time_obj)

This should work since you will be using the module.

Upvotes: 1

Riccardo Bucco
Riccardo Bucco

Reputation: 15384

You need to call the timestamp method of the datetime class inside the datetime module:

datetime.datetime.timestamp(date_time_obj)

Upvotes: 1

tzaman
tzaman

Reputation: 47840

timestamp is a method on the datetime class, not the module itself. Just do:

date_time_obj.timestamp()

Or alternatively:

datetime.datetime.timestamp(date_time_obj)

Upvotes: 1

Related Questions