Mike_H
Mike_H

Reputation: 1455

Convert timestamp list to datetime list

Within my program I filter for dates. I receive them as a list of timestamps:

timestamp = [1545730073]

The type of this list is:

print(type(timestamp))

Out: <class 'int'>

To convert this list into a list of datetime / datetime64, I tried several versions of the following code:

dt_object = datetime.datetime.fromtimestamp(timestamp)
print(dt_object)

or

dt_object = [datetime.datetime.fromtimestamp(item) for item in timestamp]
print(dt_object)

I need this type to extract the date later by the following function:

import datetime

dt_object = dt_object.date()
print(dt_object)

The output of this would and should be finally Out: 2018-12-25.

Do you guys have a recommendation to tweak my code to accomplish this task?

Upvotes: 0

Views: 20978

Answers (4)

DirtyBit
DirtyBit

Reputation: 16772

Assuming the timestamps are in a list of strings/int:

import datetime as dt
timestamp = [1545730073,1645733473]   # or timestamp = ['1545730073','1645733473']

for ts in timestamp:
    print(dt.datetime.fromtimestamp(int(ts)).date())

OUTPUT:

2018-12-25
2022-02-25

EDIT:

Using list comprehension:

print([dt.datetime.fromtimestamp(int(ts)).date() for ts in timestamp])

OUTPUT:

[datetime.date(2018, 12, 25), datetime.date(2022, 2, 25)]

EDIT 2:

If you want to replace the timestamps, using enumerate():

import datetime as dt
timestamp = [1545730073,1645733473]   # or timestamp = ['1545730073','1645733473']

for indx, ts in enumerate(timestamp):
    timestamp[indx] = dt.datetime.fromtimestamp(int(ts)).date()

print(timestamp)

OUTPUT:

[datetime.date(2018, 12, 25), datetime.date(2022, 2, 25)]

Upvotes: 4

dodopy
dodopy

Reputation: 169

get string date '2018-12-25', like this

dt_object.strftime("%Y-%m-%d")

if you got timestamp list, should like this:

timestamp = [1545730073, 1545730073]
dates = [datetime.datetime.fromtimestamp(item).date() for item in timestamp]

Upvotes: 0

Loochie
Loochie

Reputation: 2472

Also you can use map,

dt_object = list(map(datetime.date.fromtimestamp, timestamp))

Upvotes: 0

Rajat
Rajat

Reputation: 118

do not write timestamp inside square brackets. Try this code work properly.

timestamp =1545730073
dt_object = datetime.datetime.fromtimestamp(timestamp)
dt_object = dt_object.date()
print(dt_object)

Upvotes: -2

Related Questions