two different second with the same date by datetime library - python

recently I discover problem in my database. 3rd party pass the data as a second and I convert this with python to date and store it to DB. But two different Seconds saved as one date.
how can I avoid this?
My code:
import datetime
A = datetime.fromtimestamp(1600194600).strftime("%Y-%m-%d %H:%M:%S")
print('A: ' , A)
B = datetime.fromtimestamp(1600198200).strftime("%Y-%m-%d %H:%M:%S")
print('B: ' , B)
And the Result is:
A: 2020-09-15 23:00:00
B: 2020-09-15 23:00:00

You can explicitly convert to UTC (aware datetime) by setting the tz argument when calling datetime.fromtimestamp. Ex:
from datetime import datetime, timezone
# Unix time / seconds since the epoch refers to UTC:
A = datetime.fromtimestamp(1600194600, tz=timezone.utc)
B = datetime.fromtimestamp(1600198200, tz=timezone.utc)
print(A.isoformat(' '))
print(B.isoformat(' '))
>>> 2020-09-15 18:30:00+00:00
>>> 2020-09-15 19:30:00+00:00
Now you can convert to a certain time zone, e.g.
from zoneinfo import ZoneInfo # Python 3.9+, for older versions use e.g. backports.zoneinfo
zone = ZoneInfo('Asia/Tehran')
A = A.astimezone(zone)
B = B.astimezone(zone)
print(A.isoformat(' '), str(A.tzinfo))
print(B.isoformat(' '), str(B.tzinfo))
>>> 2020-09-15 23:00:00+04:30 Asia/Tehran
>>> 2020-09-16 00:00:00+04:30 Asia/Tehran

Related

python strftime apply timezone or add 3 hours

I want to apply timezone for meeting_time.strftime
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
return '{} - {} UTC - {}.{}'.format(
meeting_time.strftime('%Y.%m.%d'), meeting_time.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Example of filename I got with code above- 2020.12.02 - 10.00
Filename I want - 2020.12.02 - 13.00
Original code - https://github.com/ricardorodrigues-ca/zoom-recording-downloader
You can use datetime and timedelta.
from datetime import datetime, timedelta
print((datetime.now() + timedelta(hours=3)).strftime('%Y.%m.%d - %H.%M'))
Output
2020.12.02 - 14.39
This will print the time after 3 hours from now.
Take a look at this code:
from datetime import datetime, timedelta
d = '2020.12.02 - 10.00'
result = datetime.strftime(datetime.strptime(d, '%Y.%m.%d - %H.%M') + timedelta(hours=3), '%Y.%m.%d - %H.%M')
The result will be:
'2020.12.02 - 13.00'
If all you want to do is add 3 hours, you can do it as:
new_datetime = datetime.datetime.today() + datetime.timedelta(hours=3)
This adds 3 hours to your previous datetime.
If you want to make use of timezone's, you can find about it in Python's official documentation: https://docs.python.org/3.7/library/datetime.html#datetime.tzinfo
Let us make time conversion in a standard and robust way:
In order to covert time between zones:
1- Spcify the zone in which DateTime was recorded.
2- Convert the scpecified DateTime to the required time zone.
The mentioned steps are explained in the followin example:
from datetime import datetime
from pytz import timezone
# Choose any datetime
datetime_local=datetime(2020,12,2,10,00)
print(datetime_local)
# specifiy/include the time zone in the datetime for example ('Brazil/East') (-3.00)
datetime_brazil = timezone('Brazil/East').localize(datetime_local)
print('Brazil')
print(datetime_brazil)
# Convert it to UTC time zone
datetime_utc = datetime_brazil.astimezone(timezone('Etc/Universal'))
print('UTC')
print(datetime_utc)
# Convert the time to Cairo time zone
datetime_cairo = datetime_brazil.astimezone(timezone('Africa/Cairo'))
print('Cairo')
print(datetime_cairo)
The output
2020-12-02 10:00:00
Brazil
2020-12-02 10:00:00-03:00
UTC
2020-12-02 13:00:00+00:00
Cairo
2020-12-02 15:00:00+02:00
We Can get the list of time zone by the followin code:
import pytz
for tz in pytz.all_timezones:
print(tz)
the output list:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
...
...
Applying the steps mentioned above to the code in the question,
if the recorded DateTime was in Brazil and we want to convert it to UTC so we modify the code as follows:
def format_filename(recording, file_type, recording_type):
uuid = recording['uuid']
topic = recording['topic'].replace('/', ' ').replace(':', '').replace('?', '')
rec_type = recording_type.replace("_", " ").title()
meeting_time = parse(recording['start_time'])
# Start of modification
# Sepcify the local time zone, (localize it)
meeting_timt_local = timezone('Brazil/East').localize(meeting_time)
# Convert specified/localized DateTime to utc
meeting_time_utc = meeting_timt_local.astimezone(timezone('Etc/Universal'))
# return the formated meeting_time in utc
return '{} - {} UTC - {}.{}'.format(
meeting_time_utc.strftime('%Y.%m.%d'), meeting_time_utc.strftime('%H.%M %p'), topic+" - "+rec_type, file_type.lower())
Goog Luck

Python get local timezone offset in hours [duplicate]

In Python, how do you find what UTC time offset the computer is set to?
time.timezone:
import time
print -time.timezone
It prints UTC offset in seconds (to take into account Daylight Saving Time (DST) see time.altzone:
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
where utc offset is defined via: "To get local time, add utc offset to utc time."
In Python 3.3+ there is tm_gmtoff attribute if underlying C library supports it:
utc_offset = time.localtime().tm_gmtoff
Note: time.daylight may give a wrong result in some edge cases.
tm_gmtoff is used automatically by datetime if it is available on Python 3.3+:
from datetime import datetime, timedelta, timezone
d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)
To get the current UTC offset in a way that workarounds the time.daylight issue and that works even if tm_gmtoff is not available, #jts's suggestion to substruct the local and UTC time can be used:
import time
from datetime import datetime
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
To get UTC offset for past/future dates, pytz timezones could be used:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # local timezone
d = datetime.now(tz) # or some other local date
utc_offset = d.utcoffset().total_seconds()
It works during DST transitions, it works for past/future dates even if the local timezone had different UTC offset at the time e.g., Europe/Moscow timezone in 2010-2015 period.
gmtime() will return the UTC time and localtime() will return the local time so subtracting the two should give you the utc offset.
From https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html
The gmtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).
So, despite the name gmttime, the function returns UTC.
I like:
>>> strftime('%z')
'-0700'
I tried JTS' answer first, but it gave me the wrong result. I'm in -0700 now, but it was saying I was in -0800. But I had to do some conversion before I could get something I could subtract, so maybe the answer was more incomplete than incorrect.
the time module has a timezone offset, given as an integer in "seconds west of UTC"
import time
time.timezone
You can use the datetime and dateutil libraries to get the offset as a timedelta object:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
Create a Unix Timestamp with UTC Corrected Timezone
This simple function will make it easy for you to get the current time from a MySQL/PostgreSQL database date object.
def timestamp(date='2018-05-01'):
return int(time.mktime(
datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
)) + int(time.strftime('%z')) * 6 * 6
Example Output
>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200
Here is some python3 code with just datetime and time as imports. HTH
>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
... strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
... minute = (time.localtime().tm_gmtoff / 60) % 60
... hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
... utcoffset = "%.2d%.2d" %(hour, minute)
... if utcoffset[0] != '-':
... utcoffset = '+' + utcoffset
... return strdate + utcoffset
...
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'
This works for me:
if time.daylight > 0:
return time.altzone
else:
return time.timezone

Converting datetime to strptime

I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).

Python datetime add

I have a datetime value in string format. How can I change the format from a "-" separated date to a "." separated date. I also need to add 6 hours to let the data be in my time zone.
s = '2013-08-11 09:48:49'
from datetime import datetime,timedelta
mytime = datetime.strptime(s,"%Y-%m-%d %H:%M:%S")
time = mytime.strftime("%Y.%m.%d %H:%M:%S")
dt = str(timedelta(minutes=6*60)) #6 hours
time+=dt
print time
print dt
I get the following result where it adds the six hours at the end and not to the nine:
2013.08.11 09:48:496:00:00
6:00:00
You are adding the string representation of the timedelta():
>>> from datetime import timedelta
>>> print timedelta(minutes=6*60)
6:00:00
Sum datetime and timedelta objects, not their string representations; only create a string after summing the objects:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")
This results in:
>>> from datetime import datetime, timedelta
>>> s = '2013-08-11 09:48:49'
>>> mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
>>> mytime += timedelta(hours=6)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
However, you probably want to use real timezone objects instead, I recommend you use the pytz library:
>>> from pytz import timezone, utc
>>> eastern = timezone('US/Eastern')
>>> utctime = utc.localize(datetime.strptime(s, "%Y-%m-%d %H:%M:%S"))
>>> local_tz = utctime.astimezone(eastern)
>>> print mytime.strftime("%Y.%m.%d %H:%M:%S")
2013.08.11 15:48:49
This will take into account daylight saving time too, for example.

Getting computer's UTC offset in Python

In Python, how do you find what UTC time offset the computer is set to?
time.timezone:
import time
print -time.timezone
It prints UTC offset in seconds (to take into account Daylight Saving Time (DST) see time.altzone:
is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)
where utc offset is defined via: "To get local time, add utc offset to utc time."
In Python 3.3+ there is tm_gmtoff attribute if underlying C library supports it:
utc_offset = time.localtime().tm_gmtoff
Note: time.daylight may give a wrong result in some edge cases.
tm_gmtoff is used automatically by datetime if it is available on Python 3.3+:
from datetime import datetime, timedelta, timezone
d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)
To get the current UTC offset in a way that workarounds the time.daylight issue and that works even if tm_gmtoff is not available, #jts's suggestion to substruct the local and UTC time can be used:
import time
from datetime import datetime
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
To get UTC offset for past/future dates, pytz timezones could be used:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
tz = get_localzone() # local timezone
d = datetime.now(tz) # or some other local date
utc_offset = d.utcoffset().total_seconds()
It works during DST transitions, it works for past/future dates even if the local timezone had different UTC offset at the time e.g., Europe/Moscow timezone in 2010-2015 period.
gmtime() will return the UTC time and localtime() will return the local time so subtracting the two should give you the utc offset.
From https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html
The gmtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).
So, despite the name gmttime, the function returns UTC.
I like:
>>> strftime('%z')
'-0700'
I tried JTS' answer first, but it gave me the wrong result. I'm in -0700 now, but it was saying I was in -0800. But I had to do some conversion before I could get something I could subtract, so maybe the answer was more incomplete than incorrect.
the time module has a timezone offset, given as an integer in "seconds west of UTC"
import time
time.timezone
You can use the datetime and dateutil libraries to get the offset as a timedelta object:
>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
Create a Unix Timestamp with UTC Corrected Timezone
This simple function will make it easy for you to get the current time from a MySQL/PostgreSQL database date object.
def timestamp(date='2018-05-01'):
return int(time.mktime(
datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
)) + int(time.strftime('%z')) * 6 * 6
Example Output
>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200
Here is some python3 code with just datetime and time as imports. HTH
>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
... strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
... minute = (time.localtime().tm_gmtoff / 60) % 60
... hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
... utcoffset = "%.2d%.2d" %(hour, minute)
... if utcoffset[0] != '-':
... utcoffset = '+' + utcoffset
... return strdate + utcoffset
...
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'
This works for me:
if time.daylight > 0:
return time.altzone
else:
return time.timezone

Categories