Convert datetime to local time - python

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?

Related

Date String in Datetime Format Python

Here is my error I do not manage to solve
ValueError: time data '1/31/2021 22:59' does not match format '%d/%m/%Y %H:%M:%S'
Here is my code
90% of the time my String date I need to convert goes in my try part and It works, I have a problem with my second part.
def StringToDateTime(DateString):
from datetime import datetime
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
The error you're seeing is due to the str not having a seconds value -- the %S of the datetime format string.
Change the format string so it doesn't have the seconds placeholder, and it should work as expected:
try:
# Remove the %S from the format string here
return datetime.strptime(DateString, '%Y-%m-%d %H:%M')
except:
DateString = str(DateString)+':00'
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')
Or, if you want to alter the DateString as you do in your except clause:
# Add the seconds to the date string
DateString = f"{DateString}:00"
try:
return datetime.strptime(DateString, '%Y-%m-%d %H:%M:%S')
except:
return datetime.strptime(DateString, '%d/%m/%Y %H:%M:%S')

Determine if datetime is before or after midday

I'm working in small test code to determine if a generated datetime is before or after the midday like the code below.
import random
from datetime import datetime, timedelta
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date < datetime.time(12):
print("test")
The problem is, I can't verify if the new_date is under the midday. Probably I'm doing something wrong in the if condition, right?
I would like to print some results if the new_dateis after midday and another message if it's after midday to midnight.
Any suggestions how I can solve this?
You need to compare just the time from new_date, with 12 converted to a datetime object.
Because of the way you did the imports, when you use datetime.time() it means you are calling datetime.datetime.time() and not datetime.time(), which is why the conversion fails.
You can solve this by
from datetime import datetime, timedelta, time
and then use
time()
or by
import datetime as dt
then using in the appropriate places
dt.datetime(), dt.timedelta(), dt.time()
Complete code:
import random
from datetime import datetime, timedelta, time
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date.time() < time(12):
print("test")
Compare to new_date.hour, instead of datetime.time()
import random
from datetime import datetime, timedelta
from pytz import timezone
current_date = datetime.now(timezone('America/Sao_Paulo'))
new_date = current_date - timedelta(days=2)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
while new_date <= current_date:
new_date = new_date + timedelta(minutes=10)
print (new_date.strftime("%Y-%m-%d %H:%M:%S"))
if new_date.hour < 12:
print("before noon")
elif new_date.hour >= 18:
print("after 6 pm")

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

Adding seconds to ISO 8601 datestamp string

I am trying to add seconds to a datestamp string that is received from a json object but the datetime function I am trying to use does not allow strings and wants the date to be separated like: datetime.strftime(2011,11,18). Here is what I have:
import requests
from datetime import datetime
def call():
pay = {'token' : "802ba928cd3ce9acd90595df2853ee2b"}
r = requests.post('http://challenge.code2040.org/api/dating',
params=pay)
response = r.json()
time = response['datestamp']
interval = response['interval']
utc = datetime.strftime(time, '%Y-%m-%dT&H:%M:%S.%fZ')
timestamp = (utc-time).total_seconds()
utc_dt = datetime(time) + timedelta(seconds=timestamp)
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
Is there another way I can add time to a ISO8601 datestamp?

Python: timezone.localize() not working

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)

Categories

Resources