Python: timezone.localize() not working - python

I am having some issues getting timezone.localize() to work correctly. My goal is to grab today's date and convert it from CST to EST. Then finally format the datetime before spitting it out. I am able to format the date correctly, but the datetime is not changing from CST to EST. Additionally when I format the date I don't see the text representation of the timezone included.
Below I have listed out a simple program I created to test this out:
#! /usr/bin/python
#Test script
import threading
import datetime
import pexpect
import pxssh
import threading
from pytz import timezone
import pytz
est = timezone('US/Eastern')
curtime = est.localize(datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y"))
#test time change
#curtime = datetime.datetime.now().strftime("%a %b %d %H:%M:%S %Z %Y")
class ThreadClass(threading.Thread):
def run(self):
#now = (datetime.datetime.now() + datetime.timedelta(0, 3600))
now = (datetime.datetime.now())
print "%s says Hello World at time: %s" % (self.getName(), curtime)
for i in range(3):
t = ThreadClass()
t.start()

.localize() takes a naive datetime object and interprets it as if it is in that timezone. It does not move the time to another timezone. A naive datetime object has no timezone information to be able to make that move possible.
You want to interpret now() in your local timezone instead, then use .astimezone() to interpret the datetime in another timezone:
est = timezone('US/Eastern')
cst = timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
est_curtime = curtime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
def run(self):
print("%s says Hello World at time: %s" % (self.getName(), est_curtime))

Use cst.localize to make a naive datetime into a timezone-aware datetime.
Then use astimezone to convert a timezone-aware datetime to another timezone.
import pytz
import datetime
est = pytz.timezone('US/Eastern')
cst = pytz.timezone('US/Central')
curtime = cst.localize(datetime.datetime.now())
curtime = curtime.astimezone(est)

Related

python: logging:: get the current time in a custom timezone

I am trying the following code to log using the timezone 'America/New_York'
the time is shown correct, but the %z and %Z are not showing the right time Zone
from datetime import datetime
from pytz import timezone
import logging
def timetz(*args):
tz = timezone('America/New_York')
print(tz)
dt = datetime.now(tz)
print(dt)
return dt.timetuple()
logger = logging.getLogger()
formatter = logging.Formatter(fmt='%(asctime)s::%(levelname)-8s\n%(message)s',datefmt='%Y-%m-%d %H:%M:%S %p %Z %z')
formatter.converter = timetz
formatter.default_msec_format = '%s.%03d'
handler= logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
logger.error('test')
I get
2021-03-05 14:53:04 PM UTC +0000::ERROR
test
But i should get
2021-03-05 14:53:04 PM EST -0500::ERROR
test
The %z and %Z are not working

Convert datetime to local time

I'm doing a parse from string ISO8601 to a datetime and it's working. Now I want to return datetime on localtime but my code is returning same timestamp from input:
def format_string_to_timestamp(dt, defaultTimezone='America/Sao_Paulo'):
origin_dt = datetime.strptime(dt, '%Y-%m-%dT%H:%M:%S.%f')
tz_local = pytz.timezone (defaultTimezone)
dt_local = origin_dt.astimezone(tz_local).replace(tzinfo=None)
print(dt)
print(dt_local)
print(origin_dt)
return dt_local.strftime('%Y-%m-%d %H:%M:%S')
# example input: 2019-02-25T17:58:53.753
What is missing to return dt_local as America/Sao_Paulo timezone?

Python CSV Finding average time taken

I am trying to find the average time taken. The value 'x' will allow me to get the time taken for every row there is, but how am I able to find the average time taken for all the rows. I will think it is something like x divided by count, but I am not able to find a solution to this... any pros out there can help me??
import datetime,time,csv
from itertools import islice
from Tkinter import Tk #python GUI programming
from tkFileDialog import askopenfilename
from collections import Counter
from datetime import datetime
import pandas
Tk().withdraw()
category_list=[]
description_list=[]
reported_date=[]
acknowledged_date=[]
count = 0
# hard code all possible date formats
date_formats = ['%m/%d/%Y %H:%M', '%-d-%b-%y', '%d/%m/%Y %h:%M %p', '%d/%m/%Y %H:%M', '%A, %d %B %Y %H:%M','%A, %d %B %Y %H:%M','%A %d %B %Y %H%M',"%d/%m/%Y %H:%M %p"," %d/%m/%Y %H:%M %p", '%d-%b-%y' ,
'%d.%m.%Y', '%d %b %Y %H%M hrs', '%d %b %Y %H%M', '%d-%m-%y', '%d-%b-%y', '%b-%d-%y', '%d-%a-%y','%e-%a-%y','%b %d %Y %H%M hrs','%d/%b/%Y %m:%M %p','%A, %e %B %Y %H:%M',' %d/%m/%Y %h:%M','%d-%b-%y','%m/%d/%Y %H:%M:%S %p']
#file = askopenfilename() #ask user which file to open
#f = open(file,'r')
with open('Feedback and Complaints_Sample Dataset.csv', 'rb') as f:
reader = csv.reader(f)
header = next(reader) #read 2nd line onwards
data= [] #make a list called data
for row in reader: #assign data in every column and name them respectively
for format in date_formats:
try:
reported_on = datetime.strptime(row[0], format) #try and get the dates
acknowledged_on = datetime.strptime(row[12], format) #try and get the dates
x= acknowledged_on-reported_on #time taken to acknowledge
#acknowledged_date.append(acknowledged_on)
#reported_date.append(reported_on)
count += 1
break # if correct format, dont test any other formats
except ValueError:
pass # if incorrect format, try other formats`enter code here`
Subtracting two datetime objects creates a timedelta object. You need to keep a total time, so create a timedelta object, and for each x add it to your total.
At the end, you can then divide your total_time by your count:
import csv
from itertools import islice
from datetime import datetime, timedelta
count = 0
total_time = timedelta()
# hard code all possible date formats
date_formats = ['%m/%d/%Y %H:%M', '%-d-%b-%y', '%d/%m/%Y %h:%M %p', '%d/%m/%Y %H:%M', '%A, %d %B %Y %H:%M','%A, %d %B %Y %H:%M','%A %d %B %Y %H%M',"%d/%m/%Y %H:%M %p"," %d/%m/%Y %H:%M %p", '%d-%b-%y' ,
'%d.%m.%Y', '%d %b %Y %H%M hrs', '%d %b %Y %H%M', '%d-%m-%y', '%d-%b-%y', '%b-%d-%y', '%d-%a-%y','%e-%a-%y','%b %d %Y %H%M hrs','%d/%b/%Y %m:%M %p','%A, %e %B %Y %H:%M',' %d/%m/%Y %h:%M','%d-%b-%y','%m/%d/%Y %H:%M:%S %p']
with open('Feedback and Complaints_Sample Dataset.csv', 'rb') as f:
reader = csv.reader(f)
header = next(reader) #read 2nd line onwards
for row in reader:
for format in date_formats:
try:
reported_on = datetime.strptime(row[0], format) #try and get the dates
acknowledged_on = datetime.strptime(row[12], format) #try and get the dates
x = acknowledged_on - reported_on #time taken to acknowledge
total_time += x
count += 1
break # if correct format, don't test any other formats
except ValueError:
pass # if incorrect format, try other formats`enter code here`
print "Total time taken:", total_time
print "Average time taken:", total_time / count
Note: your logic for the date_formats implies that both dates in a single row will always share the same date format.

TypeError when converting datetime object in to UTC

I have the input date of 2017-08-22T11:32:31+10:00
I wish to convert this to UTC which would be 2017-08-22+01:32:31
Code so far
from datetime import datetime, timedelta
from pytz import timezone
import pytz
fmt = "%Y-%m-%d+%H:%M:%S"
now_time = datetime('2017-08-22T11:32:31+10:00')
zone = 'UTC'
now_time = now_time.timezone(zone)
print now_time.strftime(fmt)
Error
now_time = datetime('2017-08-22T11:32:31+10:00')
TypeError: an integer is required
You can use dateutil.parser to infer the datetime format when creating your datetime object.
import dateutil.parser
your_date = dateutil.parser.parse('2017-08-22T11:32:31+10:00')
Next, you can use the .astimezone function to convert your_date to UTC:
utc_date = your_date.astimezone(pytz.utc)
print(utc_date)
Output:
2017-08-22 01:32:31+00:00

Python current time comparison with other time

I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like "01:23:00".
import time
ctime = time.strptime("%H:%M:%S") # this always takes system time
time2 = "08:00:00"
if (ctime > time2):
print("foo")
import datetime
now = datetime.datetime.now()
my_time_string = "01:20:33"
my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S")
# I am supposing that the date must be the same as now
my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime.time().second, microsecond=0)
if (now > my_datetime):
print("Hello")
EDIT:
The above solution was not taking into account leap second days (23:59:60). Below is an updated version that deals with such cases:
import datetime
import calendar
import time
now = datetime.datetime.now()
my_time_string = "23:59:60" # leap second
my_time_string = now.strftime("%Y-%m-%d") + " " + my_time_string # I am supposing the date must be the same as now
my_time = time.strptime(my_time_string, "%Y-%m-%d %H:%M:%S")
my_datetime = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=calendar.timegm(my_time))
if (now > my_datetime):
print("Foo")
https://docs.python.org/2/library/datetime.html
The datetime module will parse dates, times, or combined date-time values into objects that can be compared.
from datetime import datetime
current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12
mytime = "10:12:34"
if current_time > mytime:
print "Time has passed."

Categories

Resources