Python 2.7 - Time offset conversion - python

Using Python 2.7, how can I convert a given time from one offset to another? My solution below treats offsets as a time and ignores the sign (+/-) leading to incorrect conversions.
import time
from datetime import datetime
import re
# inputs (cannot change)
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '-0100'
# conversion
from_time = time.strptime(from_time_str, '%H:%M')
from_offset_time = time.strptime(from_offset, '-%H%M')
to_offset_time = time.strptime(to_offset, '-%H%M')
offset_diff = abs(time.mktime(to_offset_time) - time.mktime(from_offset_time))
to_timestamp = offset_diff + time.mktime(from_time)
to_datetime = datetime.fromtimestamp(to_timestamp)
print to_datetime.strftime('%H:%M')
Output:
19:45
+/-:
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '+0700'
to_offset_time = time.strptime(to_offset, '+%H%M')
Output:
13:45

if you're open to using the dateutil library, this seems to work:
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
# inputs (cannot change)
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '-0100'
if from_offset[0]=='-':
non_offset = parse(from_time_str)+relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))
else:
non_offset = parse(from_time_str)-relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))
if to_offset[0]=='-':
to_offset_time = non_offset-relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))
else:
to_offset_time = non_offset+relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))
print to_offset_time.strftime('%H:%M')
I'm sure there is a more pythonic way, but it does seem to work!

Related

Python convert string in iso format %Y-%m-%dT%H:%M:%S.%fZ to datetime (from Microsoft APIs)

I am getting datetime strings in the format %Y-%m-%dT%H:%M:%S.%fZ from Microsoft APIs.
I have managed to convert the datetime strings to datetime with the following satements:
try:
datetime_dt = datetime.fromisoformat(datetime_string[:23].replace("Z","").ljust(23,'0'))
except:
datetime_dt = datetime.fromisoformat(datetime_string[:23].replace("Z",".").ljust(23,'0'))
However I dont find them very readable so I wanted to try to make it easier to read. I therefore implemented the following code, that works on some dates coming from Microsoft APIs:
datetime_dt = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ")
This is my python code for testing diffrent dates:
from datetime import datetime
def test():
datetime_strings: list = ['2022-05-21T12:53:10.87Z', '2022-05-21T12:53:10.855Z', '2022-05-20T19:28:08.4937187Z',
'2022-05-20T12:26:03.697Z', '2022-05-03T12:50:46.066Z', '2022-05-02T08:03:24.3013769Z',
'2022-05-02T08:03:23.3638575Z', '2022-05-02T08:01:15.0637853Z',
'2022-05-02T08:00:58.9986025Z', '2022-05-02T08:00:57.8159107Z',
'2022-04-23T11:40:11.673Z', '2022-05-11T15:27:47.0792967Z', '2022-05-05T07:49:59Z',
'2022-04-13T13:10:10.3923041Z', '2022-03-31T12:20:20.1330341Z', '2022-05-23T13:46:15.55Z',
'2022-05-20T16:11:24.7466667Z', '2022-05-20T16:01:07.13Z', '2022-05-20T15:56:05.5Z',
'2022-05-20T15:50:50.7Z', '2022-05-20T15:45:24.61Z', '2022-05-13T01:13:42.59Z',
'2022-05-12T23:56:23.0366667Z', '2022-05-12T11:55:24.52Z', '2022-05-09T13:58:48.2966667Z',
'2022-05-07T14:17:08.76Z', '2022-05-05T03:46:09.66Z', '2022-05-05T03:10:13.47Z',
'2022-05-04T06:15:46.1833333Z', '2022-05-04T06:15:46.0966667Z', '2022-05-04T06:15:46Z',
'2022-05-04T06:15:45.9133333Z', '2022-05-04T06:10:22.6766667Z', '2022-05-04T02:49:33.9Z',
'2022-05-04T02:44:03.3Z', '2022-04-28T04:33:55.3033333Z', '2022-04-26T12:55:44.82Z',
'2022-05-24T03:37:59.693Z', '2022-05-24T02:55:50.5443377Z',
'2022-05-24T02:55:09.7377354Z', '2022-05-23T10:40:37.181Z', '2022-05-23T10:40:39.832Z',
'2022-05-23T11:01:05.149Z', '2022-05-21T12:53:07.772Z', '2022-05-20T06:56:24.4908847Z',
'2022-05-19T14:25:41.342Z', '2022-05-19T13:10:19.9427916Z',
'2022-05-18T06:25:40.8578326Z', '2022-05-17T15:19:46.7617324Z',
'2022-05-17T12:20:25.624Z', '2022-05-17T05:31:34.776577Z', '2022-05-16T10:55:17.579Z',
'2022-05-16T10:55:32.485Z', '2022-05-14T13:11:46.967Z', '2022-05-14T12:08:20.96Z',
'2022-05-13T14:36:43.8287009Z', '2022-05-13T12:33:12.838Z', '2022-05-13T12:33:04.798Z',
'2022-05-13T09:40:39.265Z', '2022-05-13T09:17:45.804Z', '2022-05-13T08:20:27.7688983Z',
'2022-05-13T08:18:36.4438425Z', '2022-05-13T07:55:26.2545975Z',
'2022-05-13T07:40:22.0487128Z', '2022-05-10T19:55:29.789Z', '2022-05-10T16:59:27.023Z',
'2022-05-10T13:56:41.364Z', '2022-05-10T12:18:11.955Z', '2022-05-08T10:48:36.528Z',
'2022-05-08T04:32:22.355Z', '2022-05-08T04:38:37.873Z', '2022-05-08T03:32:41.3421313Z',
'2022-05-07T12:48:06.846Z', '2022-05-07T12:07:08.735Z', '2022-05-05T12:08:18.663Z',
'2022-05-04T12:16:10.596Z', '2022-05-04T12:16:30.246Z', '2022-05-04T09:16:21.374Z',
'2022-05-04T07:00:24.244048Z', '2022-05-04T06:59:31.7269005Z', '2022-05-02T10:32:36.686Z',
'2022-05-01T10:40:54.257Z', '2022-04-30T19:33:54.638Z', '2022-04-30T11:49:20.872Z',
'2022-04-28T20:03:45.606Z', '2022-04-26T18:52:50.976Z', '2022-04-26T11:57:51.845Z',
'2022-04-24T13:36:48.497Z', '2022-04-24T12:06:22.329457Z', '2022-05-13T14:27:26.9621533Z',
'2022-05-23T19:17:48.6494765Z', '2022-05-22T19:15:30.2321706Z',
'2022-05-21T19:24:52.6949452Z', '2022-05-20T19:43:44.489197Z',
'2022-05-19T19:22:57.9814871Z', '2022-05-18T19:00:04.0884571Z',
'2022-05-14T19:18:50.7477334Z', '2022-05-13T19:31:57.7458778Z',
'2022-05-12T19:31:07.855501Z', '2022-05-12T19:31:07.8557112Z',
'2022-05-11T19:48:58.7652378Z', '2022-05-08T18:59:30.0053174Z',
'2022-05-07T19:28:47.1721395Z', '2022-05-06T19:43:04.2483052Z',
'2022-05-05T19:27:32.5868192Z', '2022-05-04T20:01:09.3192664Z',
'2022-05-04T06:35:25.5159052Z', '2022-05-03T19:25:36.4903871Z',
'2022-05-02T19:13:26.719592Z', '2022-05-01T18:41:25.4854639Z',
'2022-04-30T19:32:35.9602448Z', '2022-04-29T19:36:31.0237008Z',
'2022-04-28T19:08:02.2903379Z', '2022-04-27T19:10:17.9105162Z',
'2022-04-26T19:00:50.5147888Z', '2022-04-25T18:45:37.814625Z',
'2022-04-24T18:46:42.4524662Z', '2022-04-23T19:19:03.4143462Z',
'2022-05-24T10:31:25.9855625Z', '2022-05-24T08:45:39.2932887Z',
'2022-05-24T08:48:19.1032321Z', '2022-05-19T16:17:53.4508148Z',
'2022-05-23T17:59:49.4340112Z', '2022-05-23T10:00:18.6608461Z',
'2022-05-20T07:39:30.2418091Z', '2022-05-20T07:40:24.1364661Z',
'2022-05-23T02:56:34.3912121Z', '2022-05-23T00:00:29.7826432Z',
'2022-05-22T14:28:12.1796409Z', '2022-05-22T14:28:12.4307055Z',
'2022-05-18T13:05:52.3632517Z', '2022-05-18T13:03:37.5704608Z',
'2022-05-22T07:07:03.3442209Z', '2022-05-21T04:16:44.7169572Z',
'2022-05-21T04:36:27.2433655Z', '2022-05-13T12:56:06.7145134Z',
'2022-05-13T04:47:03.9847257Z', '2022-05-13T04:40:42.1666622Z',
'2022-05-20T14:20:06.9364813Z', '2022-05-20T12:19:18.5476475Z',
'2022-05-17T11:34:52.6272395Z', '2022-05-20T07:13:54.9125274Z',
'2022-05-20T06:34:14.4883799Z', '2022-05-20T05:18:40.434202Z',
'2022-05-20T05:18:40.5452387Z', '2022-05-19T09:38:07.7007421Z',
'2022-05-13T07:10:12.9688778Z', '2022-05-13T07:10:37.1814015Z',
'2022-05-19T07:58:33.0648007Z', '2022-05-19T07:58:41.34596Z',
'2022-05-19T05:50:59.8623322Z', '2022-05-18T13:04:28.9649219Z',
'2022-05-19T03:18:21.8892563Z', '2022-05-16T01:45:36.4615012Z',
'2022-05-19T00:01:33.8095046Z', '2022-05-12T14:46:57.6680255Z',
'2022-05-17T17:20:11.320066Z', '2022-05-18T09:05:47.1063398Z',
'2022-05-15T07:38:13.8457309Z', '2022-05-11T07:50:30.1778153Z',
'2022-05-11T07:51:43.8967792Z', '2022-05-17T23:55:20.0350619Z',
'2022-05-17T10:06:25.3739418Z', '2022-05-17T04:50:48.4494898Z',
'2022-05-16T03:08:46.9660711Z', '2022-05-16T03:08:36.5121208Z',
'2022-05-16T09:44:54.8625426Z', '2022-05-16T07:06:49.1959797Z',
'2022-05-16T07:06:49.404664Z', '2022-05-16T07:06:53.8535994Z',
'2022-05-16T07:04:19.6062729Z', '2022-05-16T00:27:47.7054273Z',
'2022-05-15T17:23:44.477946Z', '2022-05-12T16:46:04.0401787Z',
'2022-05-12T12:41:49.7102545Z', '2022-05-12T09:43:35.4637809Z',
'2022-05-15T06:25:04.8418075Z', '2022-05-12T09:17:11.00459Z',
'2022-05-11T09:01:51.591991Z', '2022-05-14T03:50:19.7817166Z',
'2022-05-13T12:54:18.7723057Z', '2022-05-13T19:34:38.5072555Z',
'2022-05-13T10:18:47.3646313Z', '2022-05-10T14:34:32.9029436Z',
'2022-05-13T03:04:52.1918196Z', '2022-05-13T03:04:37.5657655Z',
'2022-05-13T03:04:35.3630847Z', '2022-05-12T23:57:49.5734863Z',
'2022-04-26T21:42:47.2897619Z', '2022-05-12T12:38:55.676044Z',
'2022-05-12T12:43:40.3553349Z', '2022-05-12T09:19:27.2796139Z',
'2022-05-12T08:32:38.7445013Z', '2022-05-11T12:07:24.3272769Z',
'2022-05-11T02:17:33.5859099Z', '2022-05-10T14:34:49.8803821Z',
'2022-05-10T11:02:34.5654021Z', '2022-05-10T09:27:13.6478312Z',
'2022-05-10T05:34:26.8583387Z', '2022-05-09T23:52:04.3269006Z',
'2022-05-06T22:07:18.5035095Z', '2022-05-09T09:40:39.5292833Z',
'2022-05-09T04:10:39.9505795Z', '2022-05-08T23:12:46.0831845Z',
'2022-05-08T03:02:51.5957394Z', '2022-05-07T07:28:46.7282836Z',
'2022-05-06T16:05:11.3886869Z', '2022-05-06T13:14:08.7917444Z',
'2022-05-06T13:47:21.2260805Z', '2022-05-06T10:02:59.5692441Z',
'2022-05-06T08:15:07.9529308Z', '2022-05-02T15:19:03.4035812Z',
'2022-04-28T11:58:35.0722193Z', '2022-05-05T09:45:38.0202998Z',
'2022-05-04T07:25:19.8043341Z', '2022-05-03T12:58:46.3610086Z',
'2022-04-29T13:19:26.1767962Z', '2022-05-03T03:30:11.4898688Z',
'2022-04-29T13:47:43.5590802Z', '2022-04-29T13:47:56.4814807Z',
'2022-04-29T14:30:36.2471786Z', '2022-04-29T00:08:56.8608395Z',
'2022-04-29T00:08:56.8765413Z', '2022-04-29T00:02:32.475166Z',
'2022-04-28T15:04:48.3245194Z', '2022-04-28T09:55:09.9063787Z',
'2022-04-28T10:13:46.4984867Z', '2022-04-27T08:04:33.5086013Z',
'2022-04-27T07:31:49.0128143Z', '2022-04-27T07:31:49.1345218Z',
'2022-04-27T07:11:53.6378836Z', '2022-04-27T00:01:42.8767039Z',
'2022-04-26T22:03:34.7415477Z', '2022-04-19T23:56:57.2135225Z',
'2022-04-26T06:29:55.246016Z', '2022-04-19T21:33:57.7569001Z',
'2022-04-19T07:54:08.8421957Z', '2022-04-19T07:48:34.4246219Z',
'2022-04-24T23:56:43.8841645Z', '2022-04-23T02:39:15.6609754Z',
'2022-04-23T02:39:15.6494963Z', '2022-04-23T02:39:15.8574085Z',
'2022-04-19T21:26:22.4796338Z', '2022-04-22T10:18:27.3562233Z',
'2022-04-22T09:45:57.5397436Z', '2022-04-22T10:12:56.232014Z',
'2022-04-22T10:12:41.1761689Z', '2022-04-22T08:03:03.1956902Z',
'2022-04-22T07:35:40.6899591Z', '2022-04-22T07:35:40.7203867Z',
'2022-04-22T08:15:20.4583886Z', '2022-04-21T15:23:19.0400049Z',
'2022-04-18T14:22:07.2749416Z', '2022-04-18T14:22:12.9584835Z',
'2022-04-21T08:31:04.2299502Z', '2022-04-19T06:02:06.2337764Z',
'2022-04-20T09:17:27.0170574Z', '2022-04-20T09:33:57.5431747Z',
'2022-04-20T07:24:33.9169914Z', '2022-04-20T04:11:27.4671946Z',
'2022-04-19T16:37:00.9332235Z', '2022-04-19T16:38:24.4159615Z',
'2022-04-19T09:41:27.718565Z', '2022-04-19T04:25:53.9684297Z',
'2022-04-18T16:36:15.7741698Z', '2022-04-18T16:37:59.1389429Z',
'2022-04-18T03:25:43.2635538Z', '2022-04-18T00:14:11.4833771Z',
'2022-04-17T08:06:20.4650674Z', '2022-04-17T01:22:18.3560342Z',
'2022-04-17T01:02:18.0913198Z', '2022-04-16T21:18:02.8929904Z',
'2022-04-16T21:18:02.8940377Z', '2022-04-16T21:18:47.0999094Z',
'2022-04-16T21:18:47.1754182Z', '2022-04-16T21:18:47.2373497Z',
'2022-04-16T21:18:47.2488818Z', '2022-04-16T21:18:47.3533474Z',
'2022-04-16T21:18:47.3576444Z', '2022-04-16T21:18:47.3737334Z',
'2022-04-16T21:18:47.4854437Z', '2022-04-13T09:43:30.6177682Z',
'2022-04-13T09:43:41.3352865Z', '2022-04-16T02:53:14.4760012Z',
'2022-04-15T14:58:58.7438822Z', '2022-04-15T12:15:02.458332Z',
'2022-04-15T12:15:02.4698014Z', '2022-04-15T03:17:11.7652056Z',
'2022-04-14T23:55:35.12013Z', '2022-04-14T10:29:08.6809541Z',
'2022-04-13T02:57:23.6117609Z', '2022-04-12T23:54:39.5801752Z',
'2022-04-12T23:54:56.9053632Z', '2022-04-05T04:30:18.3928507Z',
'2022-04-05T04:30:33.8749263Z', '2022-04-08T10:41:53.5521566Z',
'2022-04-08T03:42:06.7070819Z', '2022-04-10T23:57:24.6774146Z',
'2022-04-09T01:09:51.1915122Z', '2022-04-09T06:56:04.7826503Z',
'2022-04-06T04:55:45.9975601Z', '2022-04-06T04:55:46.0000473Z',
'2022-04-08T01:21:42.107782Z', '2022-04-08T01:21:42.1268773Z',
'2022-04-08T07:21:41.2183651Z', '2022-04-07T00:55:40.0889438Z',
'2022-04-06T18:43:04.1473193Z', '2022-04-06T13:08:56.2256345Z',
'2022-04-06T08:03:37.8132146Z', '2022-04-06T00:14:28.3746635Z',
'2022-04-06T00:14:32.9228781Z', '2022-04-04T01:02:31.087698Z',
'2022-04-04T01:22:42.9770108Z', '2022-04-05T14:57:10.3466447Z',
'2022-04-05T00:35:32.5099887Z', '2022-04-01T11:55:00.1637142Z',
'2022-04-04T07:03:58.3209471Z', '2022-04-04T07:04:31.9169233Z',
'2022-04-04T06:15:11.4328891Z', '2022-04-04T05:09:33.7512321Z',
'2022-04-04T05:09:49.0108033Z', '2022-04-04T00:42:02.0641304Z',
'2022-04-04T01:03:09.9220817Z', '2022-04-04T00:42:40.7861235Z',
'2022-04-03T00:29:48.394958Z', '2022-04-03T09:23:10.9012012Z',
'2022-04-03T01:30:02.7915277Z', '2022-04-03T01:30:24.2173617Z',
'2022-03-31T01:00:25.570783Z', '2022-04-02T22:48:59.847899Z',
'2022-04-02T13:30:43.174648Z', '2022-04-02T13:31:28.4626551Z',
'2022-04-02T13:30:43.2160004Z', '2022-04-02T13:29:34.9774239Z',
'2022-04-02T13:29:40.4876324Z', '2022-04-02T00:04:56.397938Z',
'2022-04-02T00:04:57.766895Z', '2022-04-01T12:59:37.6267351Z',
'2022-04-01T09:26:35.366848Z', '2022-04-01T09:27:49.3222881Z',
'2022-04-01T09:09:29.3091179Z', '2022-04-01T03:12:56.5673883Z',
'2022-04-01T00:19:32.4977288Z', '2022-04-01T00:07:55.2420928Z',
'2022-04-01T00:07:57.4635474Z', '2022-03-31T11:00:13.7859279Z',
'2022-03-31T11:01:57.5493057Z', '2022-03-31T09:19:16.9324768Z',
'2022-03-31T04:11:32.4967466Z', '2022-03-31T04:11:33.7245932Z',
'2022-03-31T01:23:38.0305693Z', '2022-03-31T01:23:57.5606335Z',
'2022-03-31T03:24:50.1558291Z', '2022-03-31T01:44:59.3651893Z',
'2022-03-31T00:47:09.8001308Z', '2022-03-31T00:08:33.9057492Z',
'2022-03-31T00:08:54.500934Z', '2022-03-30T09:52:59.3764531Z',
'2022-03-30T09:54:19.1779386Z', '2022-03-30T07:14:00.5700953Z',
'2022-03-30T07:23:08.6688133Z', '2022-03-30T05:17:10.8463648Z',
'2022-03-30T05:17:13.5880513Z', '2022-03-30T00:15:34.749897Z',
'2022-03-29T23:51:54.1154376Z', '2022-03-29T23:51:54.1515305Z',
'2022-03-29T17:28:37.872314Z', '2022-03-26T12:31:21.8602804Z',
'2022-03-29T00:58:03.5697537Z', '2022-03-28T23:38:52.5949376Z',
'2022-03-28T23:53:59.2339407Z', '2022-03-28T23:54:18.4485302Z',
'2022-03-25T11:32:44.0195012Z', '2022-03-28T10:25:30.7816353Z',
'2022-03-28T10:27:17.1202986Z', '2022-03-25T10:22:55.2149962Z',
'2022-03-28T07:09:19.9286721Z', '2022-03-28T07:09:19.9750279Z',
'2022-03-25T08:02:15.3529463Z', '2022-03-23T07:23:00.6077493Z',
'2022-03-28T00:33:25.228311Z', '2022-03-28T00:44:46.7906848Z',
'2022-03-28T00:44:55.6058241Z', '2022-03-28T00:45:59.6622676Z',
'2022-03-28T00:05:16.5728793Z', '2022-03-28T00:06:13.7802739Z',
'2022-03-24T23:02:48.6251453Z', '2022-03-24T17:38:30.8853522Z',
'2022-03-27T15:50:15.8858635Z', '2022-03-27T09:21:50.4491754Z',
'2022-03-27T09:28:47.9853986Z', '2022-03-24T10:24:29.8116578Z',
'2022-03-27T04:17:36.1110155Z', '2022-03-27T07:27:03.6839092Z',
'2022-03-27T04:00:50.9997985Z', '2022-03-27T04:01:10.5894723Z',
'2022-03-26T05:05:18.9428344Z', '2022-03-26T04:58:22.2155891Z',
'2022-03-26T04:58:35.5771334Z', '2022-03-25T16:19:32.2408379Z',
'2022-03-25T13:25:45.6113794Z', '2022-03-25T13:25:45.7308832Z',
'2022-03-25T11:08:00.8915976Z', '2022-03-25T11:32:49.7570165Z',
'2022-03-25T10:22:14.1311979Z', '2022-03-25T10:22:18.6247398Z',
'2022-03-25T09:11:40.9544766Z', '2022-03-25T09:11:41.4121881Z',
'2022-03-25T07:55:20.7699228Z', '2022-03-25T03:31:06.0074021Z',
'2022-03-25T01:07:56.0678035Z', '2022-03-25T00:21:57.6702052Z',
'2022-03-25T00:22:20.1364522Z', '2022-03-24T09:26:51.9079494Z',
'2022-03-24T09:29:23.818875Z', '2022-03-23T15:37:26.2350506Z',
'2022-03-20T17:07:21.8634705Z', '2022-03-23T09:41:15.8724386Z',
'2022-03-23T09:41:24.2317742Z', '2022-03-23T03:12:04.3361795Z',
'2022-03-23T03:12:04.4988667Z', '2022-03-23T03:12:27.1173203Z',
'2022-03-22T10:20:47.9673705Z', '2022-03-22T23:57:54.6014437Z',
'2022-03-22T23:59:35.4341649Z', '2022-03-22T10:20:48.9423859Z',
'2022-03-17T04:11:21.1741857Z', '2022-03-22T09:53:09.0676858Z',
'2022-03-22T09:44:21.7983932Z', '2022-03-22T09:45:49.7899025Z',
'2022-03-22T00:33:27.825477Z', '2022-03-22T00:33:48.4586349Z',
'2022-03-21T09:43:59.380131Z', '2022-03-21T09:44:07.5983494Z',
'2022-03-21T02:50:08.299687Z', '2022-03-21T00:03:48.3619847Z',
'2022-03-21T00:03:50.1385962Z', '2022-03-20T20:54:11.2689964Z',
'2022-03-20T09:19:37.2616423Z', '2022-03-20T09:20:58.2773709Z',
'2022-03-19T07:20:24.7603944Z', '2022-03-19T05:30:58.766272Z',
'2022-03-19T05:31:18.5162571Z', '2022-05-16T06:31:33.23Z', '2022-05-16T06:31:17.85Z',
'2022-05-16T06:31:01.447Z', '2022-05-16T06:31:01.353Z', '2022-05-16T06:31:01.317Z',
'2022-05-16T06:31:01.273Z', '2022-05-16T06:31:01.163Z', '2022-05-16T06:29:33.8Z',
'2022-05-16T06:29:25.693Z', '2022-05-16T06:29:25.587Z', '2022-05-16T06:29:25.477Z',
'2022-05-16T06:29:25.293Z', '2022-05-16T06:29:22.05Z', '2022-05-16T06:29:21.94Z',
'2022-05-16T06:29:21.833Z', '2022-05-16T06:29:21.73Z', '2022-05-16T06:28:49.35Z',
'2022-05-16T06:28:33.207Z', '2022-05-16T06:28:30.177Z', '2022-05-16T06:28:21.643Z',
'2022-05-16T06:28:21.553Z', '2022-05-16T06:28:21.463Z', '2022-05-16T06:28:21.377Z',
'2022-05-16T06:28:19.79Z', '2022-05-16T06:27:46.417Z', '2022-05-16T06:27:46.287Z',
'2022-05-16T06:27:46.173Z', '2022-05-16T06:27:46.043Z', '2022-05-16T06:27:45.923Z',
'2022-05-16T06:27:42.373Z', '2022-05-16T06:27:42.243Z', '2022-05-16T06:27:42.123Z',
'2022-05-16T06:27:36.377Z', '2022-05-16T06:27:35.687Z', '2022-05-16T06:26:31.213Z',
'2022-05-16T06:26:28.01Z', '2022-05-16T06:26:27.903Z', '2022-05-16T06:25:55.323Z',
'2022-05-16T06:25:55.21Z', '2022-05-16T06:25:51.717Z', '2022-05-16T06:25:29.56Z',
'2022-05-16T06:25:29.477Z', '2022-05-16T06:19:17.53Z', '2022-05-16T06:19:17.333Z',
'2022-05-16T02:08:04.04Z', '2022-05-14T10:10:25.89Z', '2022-05-14T10:05:24.54Z',
'2022-05-14T09:43:57.337Z', '2022-05-14T09:33:14.85Z', '2022-05-14T05:22:01.64Z',
'2022-05-13T20:44:39.187Z', '2022-05-13T20:36:18.243Z', '2022-05-13T20:36:18.123Z',
'2022-05-13T10:04:42.133Z', '2022-05-13T10:04:08.66Z', '2022-05-13T08:45:42.887Z',
'2022-05-13T07:23:46.617Z', '2022-05-13T07:23:35.123Z', '2022-05-13T07:23:35.027Z',
'2022-05-13T07:23:34.94Z', '2022-05-13T07:23:26.86Z', '2022-05-13T07:23:06.36Z',
'2022-05-13T07:22:44.99Z', '2022-05-13T07:22:44.86Z', '2022-05-13T07:22:44.16Z',
'2022-05-13T07:22:44.033Z', '2022-05-13T07:22:29.147Z', '2022-05-13T07:22:29.04Z',
'2022-05-13T07:22:28.93Z', '2022-05-13T07:22:02.02Z', '2022-05-13T07:20:36.933Z',
'2022-05-13T05:19:26.897Z', '2022-05-13T05:15:44.947Z', '2022-05-12T19:34:41.337Z',
'2022-05-12T19:34:41.23Z', '2022-05-12T17:52:15.073Z', '2022-05-12T17:40:41.833Z',
'2022-05-12T17:03:14.41Z', '2022-05-12T16:44:48.2Z', '2022-05-12T16:23:46.7Z',
'2022-05-12T16:14:57.137Z', '2022-05-12T16:13:25.137Z', '2022-05-12T15:58:58.387Z',
'2022-05-12T15:58:57.73Z', '2022-05-12T15:51:06.79Z', '2022-05-12T15:51:06.657Z',
'2022-05-12T14:30:45.377Z', '2022-05-12T11:53:42.33Z', '2022-05-12T10:00:47.143Z',
'2022-05-12T09:33:39.62Z', '2022-05-12T09:22:52.197Z', '2022-05-12T08:41:52.9Z',
'2022-05-12T08:40:56.853Z', '2022-05-12T08:40:51.76Z', '2022-05-12T08:30:45.85Z',
'2022-05-12T08:29:40.88Z', '2022-05-12T08:29:40.723Z', '2022-05-12T08:28:36.263Z',
'2022-05-12T08:06:42.15Z', '2022-05-12T08:03:49.667Z', '2022-05-12T08:03:49.213Z',
'2022-05-12T08:03:49.087Z', '2022-05-12T07:34:34.707Z', '2022-05-12T07:16:00.83Z',
'2022-05-12T07:11:00.98Z', '2022-05-12T06:56:00.593Z', '2022-05-11T14:06:17.17Z',
'2022-05-11T14:03:33.6Z', '2022-05-11T14:03:31.627Z', '2022-05-11T14:03:31.56Z',
'2022-05-11T13:45:14.863Z', '2022-05-11T13:45:14.78Z']
for datetime_string in datetime_strings:
try:
datetime_dt = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ")
print("datetime_string=" + datetime_string + " datetime_dt=" + str(datetime_dt))
except:
print("Error: datetime_string=" + datetime_string)
test()
The code gives some errors on some inputs, for example "2022-02-25T13:11:50.1867346Z":
Error: datetime_string=2022-02-25T13:11:50.1867346Z
datetime_string=2022-03-18T18:24:42.236143Z datetime_dt=2022-03-18 18:24:42.236143
Error: datetime_string=2022-03-17T21:43:11.4558792Z
datetime_string=2022-03-09T22:16:42.917888Z datetime_dt=2022-03-09 22:16:42.917888
Error: datetime_string=2022-03-01T22:06:18.6640109Z
Error: datetime_string=2022-02-25T12:24:56.6540601Z
I need to have the outputs in the example format "2022-03-09 22:16:42.917888" because I am going to check them using greater than operator on a stored timestamp later on in my code.

Python/Discord.py remove milliseconds from time.time()

I did this for my python Discord bot (basically it's a voice activity tracker), everything works fine but I want to remove the milliseconds from total_time. I would like to get something in this format '%H:%M:%S'
Is this possible ?
Here's a part of the code:
if(before.channel == None):
join_time = round(time.time())
userdata["join_time"] = join_time
elif(after.channel == None):
if(userdata["join_time"] == None): return
userdata = voice_data[guild_id][new_user]
leave_time = time.time()
passed_time = leave_time - userdata["join_time"]
userdata["total_time"] += passed_time
userdata["join_time"] = None
And here's the output:
{
"total_time": 7.4658853358879,
}
You can use a datetime.timedelta object, with some caveats.
>>> import datetime as dt
>>> data = {"total_time": 7.4658853358879}
>>> data["total_time"] = str(dt.timedelta(seconds=int(data["total_time"])))
>>> data
{'total_time': '0:00:07'}
If your time is greater than 1 day, or less than zero, the format starts including days
>>> str(dt.timedelta(days=1))
'1 day, 0:00:00'
>>> str(dt.timedelta(seconds=-1))
'-1 day, 23:59:59'
>>>

Need Assistance with stripping the microsecond from epoch time

I have an API to which I have to send a epoch time start and end date. The only issue is that it will not accept microseconds.
I built a time function using datatime, however it calculates the microseconds. I tried the .replace(microsecond=0), but that just leaves the .0 on the Epoch, which my API complains about. I also tried exporting to strptime, but then my .timestamp function fails to parse it as a string.
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
params = {'start_date':timestart.timestamp(), 'end_date':timeend.timestamp()}
i would like to basically calculate current time in Epoch and time 24 hours ago (this does not have to be super precise) that I can pass to my API.
You can simply cast (Type Conversion) the values of timestart.timestamp() and timeend.timestamp(), which are floats, to ints, i.e.:
from datetime import datetime, timedelta
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
s = int(timestart.timestamp())
e = int(timeend.timestamp())
params = {'start_date':s, 'end_date':e}
print(params)
Output:
{'start_date': 1554121647, 'end_date': 1554208047}
Demo
I usually use time.mktime() for converting datetimes to epoch time:
from datetime import datetime, timedelta
import time
timestart = datetime.now() - timedelta(hours = 24)
timeend = datetime.now()
params = {
'start_date': int(time.mktime(timestart.timetuple())),
'end_date': int(time.mktime(timeend.timetuple()))
}
# Output
{'start_date': 1554123099, 'end_date': 1554209499}
An alternative solution to Pedro's one:
from datetime import datetime
from datetime import timedelta
timestart = (datetime.now() - timedelta(hours = 24)).strftime("%s")
timeend = datetime.now().strftime("%s")
params = {'start_date':timestart,
'end_date':timeend}
Output:
{'start_date': '1554124346', 'end_date': '1554210746'}

Why is my timezone datetime wrong?

I use this code to format my time but the time that comes out is 5 hours wrong. I should be 06 something in calcutta now and it formats the time now as 01... something. What is wrong with the code?
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
tzinfo = timezone(timezoneinfo)
month = MONTHS[to_format.month - 1]
input = pytz.timezone(timezoneinfo).localize(
datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute)))
date_str = '{0} {1}'.format(input.day, _(month))
time_str = format_time(input, 'H:mm', tzinfo=tzinfo, locale=locale)
return "{0} {1}".format(date_str, time_str)
Update
This code worked which was according to the answer below.
def datetimeformat_viewad(to_format, locale='en', timezoneinfo='Asia/Calcutta'):
import datetime as DT
import pytz
utc = pytz.utc
to_format = DT.datetime(int(to_format.year), int(to_format.month), int(to_format.day), int(to_format.hour), int(to_format.minute))
utc_date = utc.localize(to_format)
tzone = pytz.timezone(timezoneinfo)
tzone_date = utc_date.astimezone(tzone)
month = MONTHS[int(tzone_date.month) - 1]
time_str = format_time(tzone_date, 'H:mm')
date_str = '{0} {1}'.format(tzone_date.day, _(month))
return "{0} {1}".format(date_str, time_str)
It sounds like to_format is a naive datetime in UTC time.
You want to convert it to Calcutta time.
To do this, you localize to_format to UTC time1, and then use astimezone to convert that timezone-aware time to Calcutta time:
import datetime as DT
import pytz
utc = pytz.utc
to_format = DT.datetime(2015,7,17,1,0)
print(to_format)
# 2015-07-17 01:00:00
utc_date = utc.localize(to_format)
print(utc_date)
# 2015-07-17 01:00:00+00:00
timezoneinfo = 'Asia/Calcutta'
tzone = pytz.timezone(timezoneinfo)
tzone_date = utc_date.astimezone(tzone)
print(tzone_date)
# 2015-07-17 06:30:00+05:30
1The tzone.localize method does not convert between timezones. It
interprets the given localtime as one given in tzone. So if to_format is
meant to be interpreted as a UTC time, then use utc.localize to convert the
naive datetime to a timezone-aware UTC time.

How to increment a datetime by one day?

How to increment the day of a datetime?
for i in range(1, 35)
date = datetime.datetime(2003, 8, i)
print(date)
But I need pass through months and years correctly? Any ideas?
date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5):
date += datetime.timedelta(days=1)
print(date)
Incrementing dates can be accomplished using timedelta objects:
import datetime
datetime.datetime.now() + datetime.timedelta(days=1)
Look up timedelta objects in the Python docs: http://docs.python.org/library/datetime.html
All of the current answers are wrong in some cases as they do not consider that timezones change their offset relative to UTC. So in some cases adding 24h is different from adding a calendar day.
Proposed solution
The following solution works for Samoa and keeps the local time constant.
def add_day(today):
"""
Add a day to the current day.
This takes care of historic offset changes and DST.
Parameters
----------
today : timezone-aware datetime object
Returns
-------
tomorrow : timezone-aware datetime object
"""
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
minute=today.minute,
second=today.second)
return tomorrow_utc_tz
Tested Code
# core modules
import datetime
# 3rd party modules
import pytz
# add_day methods
def add_day(today):
"""
Add a day to the current day.
This takes care of historic offset changes and DST.
Parameters
----------
today : timezone-aware datetime object
Returns
-------
tomorrow : timezone-aware datetime object
"""
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
tomorrow_utc_tz = tomorrow_utc_tz.replace(hour=today.hour,
minute=today.minute,
second=today.second)
return tomorrow_utc_tz
def add_day_datetime_timedelta_conversion(today):
# Correct for Samoa, but dst shift
today_utc = today.astimezone(datetime.timezone.utc)
tz = today.tzinfo
tomorrow_utc = today_utc + datetime.timedelta(days=1)
tomorrow_utc_tz = tomorrow_utc.astimezone(tz)
return tomorrow_utc_tz
def add_day_dateutil_relativedelta(today):
# WRONG!
from dateutil.relativedelta import relativedelta
return today + relativedelta(days=1)
def add_day_datetime_timedelta(today):
# WRONG!
return today + datetime.timedelta(days=1)
# Test cases
def test_samoa(add_day):
"""
Test if add_day properly increases the calendar day for Samoa.
Due to economic considerations, Samoa went from 2011-12-30 10:00-11:00
to 2011-12-30 10:00+13:00. Hence the country skipped 2011-12-30 in its
local time.
See https://stackoverflow.com/q/52084423/562769
A common wrong result here is 2011-12-30T23:59:00-10:00. This date never
happened in Samoa.
"""
tz = pytz.timezone('Pacific/Apia')
today_utc = datetime.datetime(2011, 12, 30, 9, 59,
tzinfo=datetime.timezone.utc)
today_tz = today_utc.astimezone(tz) # 2011-12-29T23:59:00-10:00
tomorrow = add_day(today_tz)
return tomorrow.isoformat() == '2011-12-31T23:59:00+14:00'
def test_dst(add_day):
"""Test if add_day properly increases the calendar day if DST happens."""
tz = pytz.timezone('Europe/Berlin')
today_utc = datetime.datetime(2018, 3, 25, 0, 59,
tzinfo=datetime.timezone.utc)
today_tz = today_utc.astimezone(tz) # 2018-03-25T01:59:00+01:00
tomorrow = add_day(today_tz)
return tomorrow.isoformat() == '2018-03-26T01:59:00+02:00'
to_test = [(add_day_dateutil_relativedelta, 'relativedelta'),
(add_day_datetime_timedelta, 'timedelta'),
(add_day_datetime_timedelta_conversion, 'timedelta+conversion'),
(add_day, 'timedelta+conversion+dst')]
print('{:<25}: {:>5} {:>5}'.format('Method', 'Samoa', 'DST'))
for method, name in to_test:
print('{:<25}: {:>5} {:>5}'
.format(name,
test_samoa(method),
test_dst(method)))
Test results
Method : Samoa DST
relativedelta : 0 0
timedelta : 0 0
timedelta+conversion : 1 0
timedelta+conversion+dst : 1 1
Here is another method to add days on date using dateutil's relativedelta.
from datetime import datetime
from dateutil.relativedelta import relativedelta
print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S')
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')
Output:
Today: 25/06/2015 20:41:44
After a Days: 01/06/2015 20:41:44
Most Simplest solution
from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
date += timedelta(days=1)
print(date)
This was a straightforward solution for me:
from datetime import timedelta, datetime
today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)
You can also import timedelta so the code is cleaner.
from datetime import datetime, timedelta
date = datetime.now() + timedelta(seconds=[delta_value])
Then convert to date to string
date = date.strftime('%Y-%m-%d %H:%M:%S')
Python one liner is
date = (datetime.now() + timedelta(seconds=[delta_value])).strftime('%Y-%m-%d %H:%M:%S')
A short solution without libraries at all. :)
d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18
Make sure that "string d" is actually in the form of %m/%d/%Y so that you won't have problems transitioning from one month to the next.

Categories

Resources