本文整理匯總了Python中datetime.datetime.strptime方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.strptime方法的具體用法?Python datetime.strptime怎麽用?Python datetime.strptime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime.datetime
的用法示例。
在下文中一共展示了datetime.strptime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: check_valid_dates
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def check_valid_dates(from_date, to_date):
"""
Check if it's a valid date range. If not raise ValueError
Inputs:
date_from - Date to scrape form
date_to - Date to scrape to
Outputs:
"""
try:
if datetime.strptime(to_date, "%Y-%m-%d") < datetime.strptime(
from_date, "%Y-%m-%d"
):
raise ValueError(
"Error: The second date input is earlier than the first one"
)
except ValueError:
raise ValueError(
"Error: Incorrect format given for dates. They must be given like 'yyyy-mm-dd' (ex: '2016-10-01')."
)
示例2: strip_tz_info
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def strip_tz_info(timestamp_format):
# strptime() doesn't allow timezone info
if '%Z' in timestamp_format:
position = timestamp_format.index('%Z')
strip_tz_fmt = PCT_Z_FMT
if '%z' in timestamp_format:
position = timestamp_format.index('%z')
strip_tz_fmt = PCT_z_FMT
if len(timestamp_format) > (position + 2):
timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
else:
timestamp_format = timestamp_format[:position]
if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
return {'strip_tz': True, 'strip_tz_fmt': strip_tz_fmt, 'timestamp_format': timestamp_format}
示例3: get_timestamp_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_timestamp_from_date_string(date_string):
""" parse a date string into unix epoch (ms) """
if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
date_string = ''.join(PCT_z_FMT.split(date_string))
if 'timestamp_format' in agent_config_vars:
if agent_config_vars['timestamp_format'] == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except e:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = 'epoch'
timestamp_localize = cli_config_vars['time_zone'].localize(timestamp_datetime)
epoch = long((timestamp_localize - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
return epoch
示例4: get_timestamp_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_timestamp_from_date_string(date_string):
""" parse a date string into unix epoch (ms) """
if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
date_string = ''.join(agent_config_vars['strip_tz_fmt'].split(date_string))
if 'timestamp_format' in agent_config_vars:
if agent_config_vars['timestamp_format'] == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = 'epoch'
timestamp_localize = cli_config_vars['time_zone'].localize(timestamp_datetime)
epoch = long((timestamp_localize - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
return epoch
示例5: strip_tz_info
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def strip_tz_info(timestamp_format):
# strptime() doesn't allow timezone info
if '%Z' in timestamp_format:
position = timestamp_format.index('%Z')
strip_tz_fmt = PCT_Z_FMT
if '%z' in timestamp_format:
position = timestamp_format.index('%z')
strip_tz_fmt = PCT_z_FMT
if len(timestamp_format) > (position + 2):
timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
else:
timestamp_format = timestamp_format[:position]
return {'strip_tz': True,
'strip_tz_fmt': strip_tz_fmt,
'timestamp_format': [timestamp_format]}
示例6: get_timestamp_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_timestamp_from_date_string(date_string):
""" parse a date string into unix epoch (ms) """
if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
date_string = ''.join(agent_config_vars['strip_tz_fmt'].split(date_string))
if 'timestamp_format' in agent_config_vars:
if agent_config_vars['timestamp_format'] == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except e:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = 'epoch'
timestamp_localize = cli_config_vars['time_zone'].localize(timestamp_datetime)
epoch = long((timestamp_localize - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
return epoch
示例7: get_datetime_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_datetime_from_date_string(date_string):
if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
date_string = ''.join(agent_config_vars['strip_tz_fmt'].split(date_string))
if 'timestamp_format' in agent_config_vars:
for timestamp_format in agent_config_vars['timestamp_format']:
try:
if timestamp_format == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string,
timestamp_format)
break
except Exception as e:
logger.info('timestamp {} does not match {}'.format(
date_string,
timestamp_format))
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = ['epoch']
return timestamp_datetime
示例8: strip_tz_info
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def strip_tz_info(timestamp_format):
# strptime() doesn't allow timezone info
if '%Z' in timestamp_format:
position = timestamp_format.index('%Z')
strip_tz_fmt = PCT_Z_FMT
if '%z' in timestamp_format:
position = timestamp_format.index('%z')
strip_tz_fmt = PCT_z_FMT
if len(timestamp_format) > (position + 2):
timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
else:
timestamp_format = timestamp_format[:position]
if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
return {'strip_tz': True,
'strip_tz_fmt': strip_tz_fmt,
'timestamp_format': [timestamp_format]}
示例9: update_data_start_time
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def update_data_start_time():
if "FileReplay" in parameters['mode'] and reporting_config_vars['prev_endtime'] != "0" and len(
reporting_config_vars['prev_endtime']) >= 8:
start_time = reporting_config_vars['prev_endtime']
# pad a second after prev_endtime
start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")));
end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval']
elif reporting_config_vars['prev_endtime'] != "0":
start_time = reporting_config_vars['prev_endtime']
# pad a second after prev_endtime
start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")));
end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval']
else: # prev_endtime == 0
end_time_epoch = int(time.time()) * 1000
start_time_epoch = end_time_epoch - 1000 * 60 * reporting_config_vars['reporting_interval']
return start_time_epoch
# update prev_endtime in config file
示例10: get_timestamp_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_timestamp_from_date_string(date_string):
""" parse a date string into unix epoch (ms) """
if 'timestamp_format' in agent_config_vars:
if agent_config_vars['timestamp_format'] == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except e:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = 'epoch'
timestamp_localize = cli_config_vars['time_zone'].localize(timestamp_datetime)
epoch = long((timestamp_localize - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
return epoch
示例11: get_timestamp_from_date_string
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_timestamp_from_date_string(date_string):
""" parse a date string into unix epoch (ms) """
if 'strip_tz' in agent_config_vars and agent_config_vars['strip_tz']:
date_string = ''.join(agent_config_vars['strip_tz_fmt'].split(date_string))
if 'timestamp_format' in agent_config_vars:
if agent_config_vars['timestamp_format'] == 'epoch':
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
else:
timestamp_datetime = datetime.strptime(date_string, agent_config_vars['timestamp_format'])
else:
try:
timestamp_datetime = dateutil.parse.parse(date_string)
except:
timestamp_datetime = get_datetime_from_unix_epoch(date_string)
agent_config_vars['timestamp_format'] = 'epoch'
timestamp_localize = cli_config_vars['time_zone'].localize(timestamp_datetime)
epoch = long((timestamp_localize - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
return epoch
示例12: copy
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def copy(settings):
# Fetch readings from GoodWe
date = datetime.strptime(settings.date, "%Y-%m-%d")
gw = gw_api.GoodWeApi(settings.gw_station_id, settings.gw_account, settings.gw_password)
data = gw.getDayReadings(date)
if settings.pvo_system_id and settings.pvo_api_key:
if settings.darksky_api_key:
ds = ds_api.DarkSkyApi(settings.darksky_api_key)
temperatures = ds.get_temperature_for_day(data['latitude'], data['longitude'], date)
else:
temperatures = None
# Submit readings to PVOutput
pvo = pvo_api.PVOutputApi(settings.pvo_system_id, settings.pvo_api_key)
pvo.add_day(data['entries'], temperatures)
else:
for entry in data['entries']:
logging.info("{}: {:6.0f} W {:6.2f} kWh".format(
entry['dt'],
entry['pgrid_w'],
entry['eday_kwh'],
))
logging.warning("Missing PVO id and/or key")
示例13: test_mondrian_datetime
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def test_mondrian_datetime(self):
d1 = datetime.strptime("2007-03-04 21:08:12", "%Y-%m-%d %H:%M:%S")
d2 = datetime.strptime("2008-03-04 21:08:12", "%Y-%m-%d %H:%M:%S")
d3 = datetime.strptime("2009-03-04 21:08:12", "%Y-%m-%d %H:%M:%S")
d4 = datetime.strptime("2007-03-05 21:08:12", "%Y-%m-%d %H:%M:%S")
data = [[6, d1, 'haha'],
[8, d1, 'haha'],
[8, d1, 'test'],
[8, d1, 'haha'],
[8, d1, 'test'],
[4, d1, 'hha'],
[4, d2, 'hha'],
[4, d3, 'hha'],
[4, d4, 'hha']]
result, eval_r = mondrian(data, 2, False)
print(eval_r)
示例14: get_datetime
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def get_datetime(self, timestamp: str, unix=True):
"""Converts a %Y%m%dT%H%M%S.%fZ to a UNIX timestamp
or a datetime.datetime object
Parameters
---------
timestamp: str
A timstamp in the %Y%m%dT%H%M%S.%fZ format, usually returned by the API
in the ``created_time`` field for example (eg. 20180718T145906.000Z)
unix: Optional[bool] = True
Whether to return a POSIX timestamp (seconds since epoch) or not
Returns int or datetime.datetime
"""
time = datetime.strptime(timestamp, '%Y%m%dT%H%M%S.%fZ')
if unix:
return int(time.timestamp())
else:
return time
示例15: last_full_backup_date
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import strptime [as 別名]
def last_full_backup_date(self):
"""
Check if last full backup date retired or not.
:return: 1 if last full backup date older than given interval, 0 if it is newer.
"""
# Finding last full backup date from dir/folder name
max_dir = self.recent_full_backup_file()
dir_date = datetime.strptime(max_dir, "%Y-%m-%d_%H-%M-%S")
now = datetime.now()
# Finding if last full backup older than the interval or more from now!
if (now - dir_date).total_seconds() >= self.full_backup_interval:
return 1
else:
return 0