Search code examples
pythondatetimeunix-timestampepochpytz

Unix epoch timestamps converted to UTC timezone in Python


For a given year this code returns readable and Unix epoch time for the start and end of the year.

How can I simplify this and get this to default to UTC time instead of local timezone? I would greatly appreciate any pointers. Thank you.

#!/usr/bin/env python3

from datetime import datetime
import pytz

tz = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S%z'

def unix_time(date):
    timestamp = datetime.strptime(date,fmt).strftime('%s')
    return str(timestamp) #unix timestamp

def first_of(year):
    first = str(datetime(year, 1, 1, tzinfo=tz)) #yyyy-01-01 00:00 
    times = [first, unix_time(first)] 
    return times

def last_of(year):
    last = str(datetime(year, 12, 31, 23, 59, tzinfo=tz)) #yyyy-12-31 23:59
    times = [last, unix_time(last)]
    return times

year = 2021
print(first_of(year), last_of(year), sep='\n')



Solution

  • Just don't do all the unnecessary casting between strings, ints and datetime objects, and your code is already a lot simpler:

    from datetime import datetime, timezone
    
    year = 2021
    first = datetime(year, 1, 1, tzinfo=timezone.utc)
    last = datetime(year, 12, 31, 59, 59, 59, tzinfo=timezone.utc)
    
    print(first, first.timestamp(), last, last.timestamp())