Home > Software design >  Running Function on all Items in a List (Converting List of Dates to Unix Timestamp)
Running Function on all Items in a List (Converting List of Dates to Unix Timestamp)

Time:11-04

I'm stuck trying to figure out what is wrong with my for loop. Why is this appending the same UNIX timestamp in all of the UNIX dates variable?

now = datetime.datetime.today()
dates = []
for x in range(7):
    d = now - timedelta(days=x)
    dates.append(d.strftime("%Y/%m/%d"))
print(dates)
unixdates = []
for date in dates:
    e = time.mktime(datetime.datetime.strptime(datetime.date.today().strftime("%m/%d/%Y"), '%m/%d/%Y').timetuple())
    unixdates.append(e)
print(unixdates)

Here is the output:

['2021/11/03', '2021/11/02', '2021/11/01', '2021/10/31', '2021/10/30', '2021/10/29', '2021/10/28']
[1635912000.0, 1635912000.0, 1635912000.0, 1635912000.0, 1635912000.0, 1635912000.0, 1635912000.0]

CodePudding user response:

because you use the same date over and over again which will always give the same UNIX time (datetime.date.today(), with datetime being the datetime module here).

simplify your code by using the datetime.timestamp method to get UNIX time:

from datetime import datetime, timedelta

today = datetime.now().date()
dates, unixdates = [], []

for x in range(7):
    d = today - timedelta(days=x)
    dates.append(d.strftime("%Y/%m/%d"))
    unixdates.append(datetime.combine(d, datetime.min.time()).timestamp())

print(dates)
print(unixdates) # my machine is on UTC 1
# ['2021/11/03', '2021/11/02', '2021/11/01', '2021/10/31', '2021/10/30', '2021/10/29', '2021/10/28']
# [1635894000.0, 1635807600.0, 1635721200.0, 1635631200.0, 1635544800.0, 1635458400.0, 1635372000.0]

Also notice that you use naive datetime here, which will assume local time if you don't set the tz argument, e.g.

today = datetime.now(timezone.utc)

to get UTC.

  • Related