GVKun编程网logo

如何在 Python 中使用 DateTime(python datetime怎么用)

1

本文将分享如何在Python中使用DateTime的详细内容,并且还将对pythondatetime怎么用进行详尽解释,此外,我们还将为大家带来关于pythondate和datetime的取值范围(对

本文将分享如何在 Python 中使用 DateTime的详细内容,并且还将对python datetime怎么用进行详尽解释,此外,我们还将为大家带来关于python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)、Python datetime 模块-datetime() 实例源码、python datetime.datetime、Python datetime.datetime 模块-astimezone() 实例源码的相关知识,希望对你有所帮助。

本文目录一览:

如何在 Python 中使用 DateTime(python datetime怎么用)

如何在 Python 中使用 DateTime(python datetime怎么用)

所有数据在开始时都会自动分配一个“DOB”(出生日期)。因此,在某些时候处理数据时不可避免地会遇到日期和时间数据。本教程将带您了解 Python 中的 datetime 模块以及使用一些外围库,如pandas 和 pytz。

在 Python 中,任何与日期和时间有关的事情都由 datetime 模块处理,它将模块进一步分为 5 个不同的类。类只是与对象相对应的数据类型。下图总结了 Python 中的 5 个日期时间类以及常用的属性和示例。

如何在 Python 中使用 DateTime

3个有用的片段

1.将字符串转换为日期时间格式 ,也许是使用datetime 最常见的情况。

由于日期和时间的字母数字性质,将类似的日期和时间解析为 Python 通常会被解释为字符串。在本节中,我们将介绍如何将字符串列表解析为日期时间格式,以及如何将日期和时间数据拆分和组合到数据框中的各个列中。

如何在 Python 中使用 DateTime

如何在 Python 中使用 DateTime

片段 1 的打印输出

但是,如果日期时间以不寻常或模棱两可的方式格式化怎么办?一个常见的问题是美国和欧洲的日期时间书写方式之间的区别。在美式格式中,月份在前,而在欧洲样式中,日期在前。

如何在 Python 中使用 DateTime

默认情况下,pandas 中的 to_datetime 通过将前一个少于 12 位 (

如何在 Python 中使用 DateTime

或者, strftime() 方法有助于在返回字符串之前格式化日期时间。在以下示例中,原始日期时间之间的破折号 (-) 替换为反斜杠 (/),数字月份 (02) 替换为缩写的英语术语 (Feb)。

如何在 Python 中使用 DateTime

由于有多种方法可以解释日期(日、月、年)和时间(时、分、秒),因此了解不同的格式代码至关重要。下表是常用格式代码的备忘单。

如何在 Python 中使用 DateTime

2.使用时区

没有时区信息的 datetime 对象被称为“naive”,有时区信息的对象(通常在末尾带有 +HH:MM 对应 GMT)被认为是“aware”。pytz 可能是 Python 中最全面的库之一,它简化了时区计算的任务。以下代码段将向您展示如何在“naive”和“aware” datetime 对象之间进行转换,并可以使用不同的时区。代码的最后一部分还演示了如何将给定的日期时间对象转换为本地时区。此示例显示了日本和德国的时区代码,对于其他地区,您可以在此处参考。

如何在 Python 中使用 DateTime

如何在 Python 中使用 DateTime

片段2的输出

3.使用interval比较两个datetime(s)

有时我们必须有条件地比较两个日期时间。想象一下,您有两个数据框,第一个数据框仅包含一列日期时间,第二个数据框包含两列表示间隔和其余列中的其他信息。您的目标是从第一个数据帧中找到匹配的日期时间,如果它落在第二个数据帧的间隔内,如果是,则复制其他列。

如何在 Python 中使用 DateTime

实现此目的的一种方法是使用 pd.Interval 压缩两个日期时间的间隔,然后将它们分配为数据框的索引,稍后可用于有条件地比较和映射日期时间。如果满足时间条件,这可以通过使用 for 循环复制感兴趣的列来完成。

如何在 Python 中使用 DateTime

原文:https://towardsdatascience.com/how-to-work-with-datetime-in-python-26d4092dc484

以上就是如何在 Python 中使用 DateTime的详细内容,更多请关注php中文网其它相关文章!

python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)

python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)

Python 的情况

先来看看 date 类型吧!

In [1]: from datetime import date

In [2]: date.min
Out[2]: datetime.date(1, 1, 1)

In [3]: str(date.min)
Out[3]: ''0001-01-01''

In [4]: str(date.max)
Out[4]: ''9999-12-31''

可以看到 python 的 date 的取值范围是 0001-01-019999-12-31

再来看看 datetime 吧!

In [5]: from datetime import datetime

In [6]: str(datetime.min)
Out[6]: ''0001-01-01 00:00:00''

In [7]: str(datetime.max)
Out[7]: ''9999-12-31 23:59:59.999999''

可以看到 python 的 datetime 的取值范围是 0001-01-01 00:00:009999-12-31 23:59:59.999999

Mysql 的情况

来看看 mysql 的情况吧,下面的官方文档中的内容:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in ''YYYY-MM-DD'' format. The supported range is ''1000-01-01'' to ''9999-12-31''.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ''YYYY-MM-DD hh:mm:ss'' format. The supported range is ''1000-01-01 00:00:00'' to ''9999-12-31 23:59:59''.

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ''1970-01-01 00:00:01'' UTC to ''2038-01-19 03:14:07'' UTC.

总结一下就是:

  • date 的取值范围:1000-01-019999-12-31
  • timestamp 的取值范围:1970-01-01 00:00:012038-01-19 03:14:07
  • datetime 的取值范围:1000-01-01 00:00:009999-12-31 23:59:59

参考资料:mysql 文档

但是需要注意:

Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type (''0000-00-00'' or ''0000-00-00 00:00:00''), if the SQL mode permits this conversion. The precise behavior depends on which if any of strict SQL mode and the NO_ZERO_DATE SQL mode are enabled; see Section 5.1.10, “Server SQL Modes”.

还有这部分:
图片.png

翻译成人话的意思,就是 myql 会把无效的 date 设为 0000-00-00,无效的 datetime 和 timestamp 设为 0000-00-00 00:00:00

比如 2022-13-35 就是一个无效的 date,当把这个值插入到 mysql 中的时候,开启了严格模式的 mysql 会报错,未开启严格模式的 mysql 会转为 0000-00-00 保存。

‼️ 所以我们使用 Python 从 mysql 读取时间类型的时候,一定要注意这个坑!因为 0000-00-00 没有办法转成 Python 的 date 类型,会报错的!‼️


顺便可以看看 Mysql 的 date、timestamp、datetime 各占用几个字节:

  • date 类型 3 字节
  • timestamp 类型 4 字节
  • datetime 类型 8 字节

图片.png

参考文章:Data Type Storage Requirements


关于 Mysql 插入的时间类型可以是 0000-00-00 这种格式的原因可以参考:MySQL Incorrect datetime value: ''0000-00-00 00:00:00''

在 Mysql8 中默认是不可以插入这种无效时间的

Python datetime 模块-datetime() 实例源码

Python datetime 模块-datetime() 实例源码

Python datetime 模块,datetime() 实例源码

我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用datetime.datetime()

项目:Easysentiment    作者:Jflick58    | 项目源码 | 文件源码
  1. def default(self, obj):
  2. """default method."""
  3. if hasattr(obj, ''__json__''):
  4. return obj.__json__()
  5. elif isinstance(obj, collections.Iterable):
  6. return list(obj)
  7. elif isinstance(obj, datetime):
  8. return obj.isoformat()
  9. elif hasattr(obj, ''__getitem__'') and hasattr(obj, ''keys''):
  10. return dict(obj)
  11. elif hasattr(obj, ''__dict__''):
  12. return {member: getattr(obj, member)
  13. for member in dir(obj)
  14. if not member.startswith(''_'') and
  15. not hasattr(getattr(obj, member), ''__call__'')}
  16.  
  17. return json.JSONEncoder.default(self, obj)
项目:cbapi-python    作者:carbonblack    | 项目源码 | 文件源码
  1. def get_response_and_time(self, key, default=(None, None)):
  2. """ Retrieves response and timestamp for `key` if it''s stored in cache,
  3. otherwise returns `default`
  4.  
  5. :param key: key of resource
  6. :param default: return this if `key` not found in cache
  7. :returns: tuple (response,datetime)
  8.  
  9. .. note:: Response is restored after unpickling with :meth:`restore_response`
  10. """
  11. try:
  12. if key not in self.responses:
  13. key = self.keys_map[key]
  14. response, timestamp = self.responses[key]
  15. except KeyError:
  16. return default
  17. return self.restore_response(response), timestamp
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
  1. def setUpTestData(cls):
  2. super().setUpTestData()
  3. cls.create_local_and_remote_user()
  4. cls.user2 = AnonymousUser()
  5. cls.local_user = UserFactory()
  6. cls.public_content = ContentFactory(
  7. visibility=Visibility.PUBLIC, text="**Foobar**", author=cls.profile,
  8. )
  9. cls.site_content = ContentFactory(
  10. visibility=Visibility.SITE, text="_Foobar_"
  11. )
  12. cls.limited_content = ContentFactory(visibility=Visibility.LIMITED)
  13. cls.self_content = ContentFactory(visibility=Visibility.SELF)
  14. cls.remote_content = ContentFactory(
  15. visibility=Visibility.PUBLIC, remote_created=make_aware(datetime.datetime(2015, 1, 1)),
  16. author=cls.remote_profile,
  17. )
  18. cls.ids = [
  19. cls.public_content.id, cls.site_content.id, cls.limited_content.id, cls.self_content.id
  20. ]
  21. cls.set = {
  22. cls.public_content, cls.site_content, cls.limited_content, cls.self_content
  23. }
项目:Easysentiment    作者:Jflick58    | 项目源码 | 文件源码
  1. def default(self, obj)
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_am_pm_behavIoUr(self):
  2. check_time = datetime.datetime(
  3. year=2016, month=11, day=7, hour=22,
  4. minute=10, second=0, microsecond=1)
  5. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  6. date_time=(check_time + datetime.timedelta(hours=-12)))
  7. self.assertTrue(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def get_time(cls, request, time_attr):
  2. """Extracts a time object from the given request
  3.  
  4. :param request: the request object
  5. :param time_attr: the attribute name
  6. :return: datetime.timedelta
  7. """
  8. time_part = datetime.datetime.strptime(
  9. request.params[time_attr][:-4],
  10. ''%a,%d %b %Y %H:%M:%s''
  11. )
  12.  
  13. return datetime.timedelta(
  14. hours=time_part.hour,
  15. minutes=time_part.minute
  16. )
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def get_datetime(cls, date_attr, time_attr):
  2. """Extracts a UTC datetime object from the given request
  3. :param request: the request object
  4. :param date_attr: the attribute name
  5. :return: datetime.datetime
  6. """
  7. date_part = datetime.datetime.strptime(
  8. request.params[date_attr][:-4],%d %b %Y %H:%M:%s''
  9. )
  10.  
  11. time_part = datetime.datetime.strptime(
  12. request.params[time_attr][:-4],%d %b %Y %H:%M:%s''
  13. )
  14.  
  15. # update the time values of date_part with time_part
  16. return date_part.replace(
  17. hour=time_part.hour,
  18. minute=time_part.minute,
  19. second=time_part.second,
  20. microsecond=time_part.microsecond
  21. )
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def coerce_to_dtype(dtype, value):
  2. """
  3. Make a value with the specified numpy dtype.
  4.  
  5. Only datetime64[ns] and datetime64[D] are supported for datetime dtypes.
  6. """
  7. name = dtype.name
  8. if name.startswith(''datetime64''):
  9. if name == ''datetime64[D]'':
  10. return make_datetime64D(value)
  11. elif name == ''datetime64[ns]'':
  12. return make_datetime64ns(value)
  13. else:
  14. raise TypeError(
  15. "Don''t kNow how to coerce values of dtype %s" % dtype
  16. )
  17. return dtype.type(value)
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def get_open_and_close(day, early_closes):
  2. market_open = pd.Timestamp(
  3. datetime(
  4. year=day.year,
  5. month=day.month,
  6. day=day.day,
  7. hour=9,
  8. minute=31),
  9. tz=''US/Eastern'').tz_convert(''UTC'')
  10. # 1 PM if early close,4 PM otherwise
  11. close_hour = 13 if day in early_closes else 16
  12. market_close = pd.Timestamp(
  13. datetime(
  14. year=day.year,
  15. hour=close_hour),
  16. tz=''US/Eastern'').tz_convert(''UTC'')
  17.  
  18. return market_open, market_close
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def create_test_panel_ohlc_source(sim_params, env):
  2. start = sim_params.first_open \\
  3. if sim_params else pd.datetime(1990, 3, 0, pytz.utc)
  4.  
  5. end = sim_params.last_close \\
  6. if sim_params else pd.datetime(1990, 8, pytz.utc)
  7.  
  8. index = env.days_in_range(start, end)
  9. price = np.arange(0, len(index)) + 100
  10. high = price * 1.05
  11. low = price * 0.95
  12. open_ = price + .1 * (price % 2 - .5)
  13. volume = np.ones(len(index)) * 1000
  14. arbitrary = np.ones(len(index))
  15.  
  16. df = pd.DataFrame({''price'': price,
  17. ''high'': high,
  18. ''low'': low,
  19. ''open'': open_,
  20. ''volume'': volume,
  21. ''arbitrary'': arbitrary},
  22. index=index)
  23. panel = pd.Panel.from_dict({0: df})
  24.  
  25. return DataPanelSource(panel), panel
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def get_open_and_close(day, early_closes):
  2. # only "early close" event in Bovespa actually is a late start
  3. # as the market only opens at 1pm
  4. open_hour = 13 if day in quarta_cinzas else 10
  5. market_open = pd.Timestamp(
  6. datetime(
  7. year=day.year,
  8. hour=open_hour,
  9. minute=00),
  10. tz=''America/Sao_Paulo'').tz_convert(''UTC'')
  11. market_close = pd.Timestamp(
  12. datetime(
  13. year=day.year,
  14. hour=16),
  15. tz=''America/Sao_Paulo'').tz_convert(''UTC'')
  16.  
  17. return market_open, market_close
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def _coerce_datetime(maybe_dt):
  2. if isinstance(maybe_dt, datetime.datetime):
  3. return maybe_dt
  4. elif isinstance(maybe_dt, datetime.date):
  5. return datetime.datetime(
  6. year=maybe_dt.year,
  7. month=maybe_dt.month,
  8. day=maybe_dt.day,
  9. tzinfo=pytz.utc,
  10. )
  11. elif isinstance(maybe_dt, (tuple, list)) and len(maybe_dt) == 3:
  12. year, month, day = maybe_dt
  13. return datetime.datetime(
  14. year=year,
  15. month=month,
  16. day=day,
  17. )
  18. else:
  19. raise TypeError(''Cannot coerce %s into a datetime.datetime''
  20. % type(maybe_dt).__name__)
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def get_open_and_close(day,
  2. tz=''Asia/Shanghai'').tz_convert(''UTC'')
  3.  
  4. return market_open, market_close
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def test_generator_dates(self):
  2. """
  3. Ensure the pipeline of generators are in sync,at least as far as
  4. their current dates.
  5. """
  6.  
  7. sim_params = factory.create_simulation_parameters(
  8. start=datetime(2011, 7, 30, tzinfo=pytz.utc),
  9. end=datetime(2012,
  10. env=self.env,
  11. )
  12. algo = TestAlgo(self, sim_params=sim_params, env=self.env)
  13. Trade_source = factory.create_daily_Trade_source(
  14. [8229],
  15. sim_params,
  16. )
  17. algo.set_sources([Trade_source])
  18.  
  19. gen = algo.get_generator()
  20. self.assertTrue(list(gen))
  21.  
  22. self.assertTrue(algo.slippage.latest_date)
  23. self.assertTrue(algo.latest_date)
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def test_progress(self):
  2. """
  3. Ensure the pipeline of generators are in sync,at least as far as
  4. their current dates.
  5. """
  6. sim_params = factory.create_simulation_parameters(
  7. start=datetime(2008,
  8. end=datetime(2008, 5,
  9. )
  10. algo.set_sources([Trade_source])
  11.  
  12. gen = algo.get_generator()
  13. results = list(gen)
  14. self.assertEqual(results[-2][''progress''], 1.0)
项目:zipline-chinese    作者:zhanghan1990    | 项目源码 | 文件源码
  1. def test_checks_should_trigger(self):
  2. class CountingRule(Always):
  3. count = 0
  4.  
  5. def should_trigger(self, dt, env):
  6. CountingRule.count += 1
  7. return True
  8.  
  9. for r in [CountingRule] * 5:
  10. self.em.add_event(
  11. Event(r(), lambda context, data: None)
  12. )
  13.  
  14. mock_algo_class = namedtuple(''FakeAlgo'', [''Trading_environment''])
  15. mock_algo = mock_algo_class(Trading_environment="fake_env")
  16. self.em.handle_data(mock_algo, None, datetime.datetime.Now())
  17.  
  18. self.assertEqual(CountingRule.count, 5)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
  1. def writeValue(self, value):
  2. if isinstance(value, (str, unicode)):
  3. self.simpleElement("string", value)
  4. elif isinstance(value, bool):
  5. # must switch for bool before int,as bool is a
  6. # subclass of int...
  7. if value:
  8. self.simpleElement("true")
  9. else:
  10. self.simpleElement("false")
  11. elif isinstance(value, (int, long)):
  12. self.simpleElement("integer", "%d" % value)
  13. elif isinstance(value, float):
  14. self.simpleElement("real", repr(value))
  15. elif isinstance(value, dict):
  16. self.writeDict(value)
  17. elif isinstance(value, Data):
  18. self.writeData(value)
  19. elif isinstance(value, datetime.datetime):
  20. self.simpleElement("date", _datetoString(value))
  21. elif isinstance(value, list)):
  22. self.writeArray(value)
  23. else:
  24. raise TypeError("unsuported type: %s" % type(value))
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
  1. def make_comparable(self, other):
  2. if isinstance(other, DateTime):
  3. s = self.value
  4. o = other.value
  5. elif datetime and isinstance(other, datetime.datetime):
  6. s = self.value
  7. o = other.strftime("%Y%m%dT%H:%M:%s")
  8. elif isinstance(other, unicode)):
  9. s = self.value
  10. o = other
  11. elif hasattr(other, "timetuple"):
  12. s = self.timetuple()
  13. o = other.timetuple()
  14. else:
  15. otype = (hasattr(other, "__class__")
  16. and other.__class__.__name__
  17. or type(other))
  18. raise TypeError("Can''t compare %s and %s" %
  19. (self.__class__.__name__, otype))
  20. return s, o
项目:cbapi-python    作者:carbonblack    | 项目源码 | 文件源码
  1. def get_response(self, default=None):
  2. """ Retrieves response and timestamp for `key` if it''s stored in cache,datetime)
  3.  
  4. .. note:: Response is restored after unpickling with :meth:`restore_response`
  5. """
  6. try:
  7. if key not in self.responses:
  8. key = self.keys_map[key]
  9. response = self.responses[key]
  10. except KeyError:
  11. return default
  12. return response
项目:tts-bug-bounty-dashboard    作者:18F    | 项目源码 | 文件源码
  1. def test_activity_sets_sla_triaged_at():
  2. r = new_report()
  3. r.save()
  4. assert r.sla_triaged_at is None
  5.  
  6. # An activity that shouldn''t update sla_triaged_at
  7. d1 = Now()
  8. r.activities.create(id=1, type=''activity-comment'', created_at=d1)
  9. assert r.sla_triaged_at is None
  10.  
  11. # And Now one that should
  12. d2 = d1 + datetime.timedelta(hours=3)
  13. r.activities.create(id=2, type=''activity-bug-not-applicable'', created_at=d2)
  14. assert r.sla_triaged_at == d2
  15.  
  16. # And Now another aciivity that would update the date,if it wasn''t already set
  17. d3 = d2 + datetime.timedelta(hours=3)
  18. r.activities.create(id=3, type=''activity-bug-resolved'', created_at=d3)
  19. assert r.sla_triaged_at == d2
项目:otRebuilder    作者:Pal3love    | 项目源码 | 文件源码
  1. def _load_date(val):
  2. microsecond = 0
  3. tz = None
  4. try:
  5. if len(val) > 19:
  6. if val[19] == ''.'':
  7. microsecond = int(val[20:26])
  8. if len(val) > 26:
  9. tz = TomlTz(val[26:32])
  10. else:
  11. tz = TomlTz(val[19:25])
  12. except ValueError:
  13. tz = None
  14. try:
  15. d = datetime.datetime(int(val[:4]), int(val[5:7]), int(val[8:10]), int(val[11:13]), int(val[14:16]), int(val[17:19]), microsecond, tz)
  16. except ValueError:
  17. return None
  18. return d
项目:deployfish    作者:caltechads    | 项目源码 | 文件源码
  1. def setUp(self):
  2. aws_data = {
  3. ''scalableTargets'': [
  4. {
  5. ''ServiceNamespace'': ''ecs'',
  6. ''ResourceId'': ''service/my_cluster/my_service'',
  7. ''scalableDimension'': ''ecs:service:DesiredCount'',
  8. ''MinCapacity'': 1,
  9. ''MaxCapacity'': 3,
  10. ''RoleARN'': ''my_role_arn'',
  11. ''CreationTime'': datetime(2017, 4, 14)
  12. }
  13. ],
  14. ''NextToken'': None
  15. }
  16. init = Mock(return_value=None)
  17. init.return_value = None
  18. appscaling_client = Mock()
  19. appscaling_client.describe_scalable_targets = Mock(return_value=aws_data)
  20. client = Mock(return_value=appscaling_client)
  21. with Replacer() as r:
  22. r.replace(''boto3.client'', client)
  23. r.replace(''deployfish.aws.appscaling.ScalingPolicy.__init__'', init)
  24. self.appscaling = ApplicationAutoscaling(''my_service'', ''my_cluster'')
项目:deployfish    作者:caltechads    | 项目源码 | 文件源码
  1. def setUp(self):
  2. aws_data = {
  3. ''ServiceNamespace'': ''ecs'',
  4. ''ResourceId'': ''service/my_cluster/my_service'',
  5. ''scalableDimension'': ''ecs:service:DesiredCount'',
  6. ''MinCapacity'': 1,
  7. ''MaxCapacity'': 3,
  8. ''RoleARN'': ''my_role_arn'',
  9. ''CreationTime'': datetime(2017, 14)
  10. }
  11. init = Mock(return_value=None)
  12. init.return_value = None
  13. appscaling_client = Mock()
  14. self.describe_scaling_targets = Mock(return_value=aws_data)
  15. appscaling_client.describe_scalable_targets = self.describe_scaling_targets
  16. client = Mock(return_value=appscaling_client)
  17. with Replacer() as r:
  18. r.replace(''boto3.client'', ''my_cluster'', aws=aws_data)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
  1. def test_edited_is_false_for_newly_created_content_within_15_minutes_grace_period(self):
  2. with freeze_time(self.public_content.created + datetime.timedelta(minutes=14)):
  3. self.public_content.save()
  4. self.assertFalse(self.public_content.edited)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
  1. def test_edited_is_true_for_newly_created_content_after_15_minutes_grace_period(self):
  2. with freeze_time(self.public_content.created + datetime.timedelta(minutes=16)):
  3. self.public_content.save()
  4. self.assertTrue(self.public_content.edited)
项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
  1. def test_dict_for_view_edited_post(self):
  2. with freeze_time(self.public_content.created + datetime.timedelta(minutes=16)):
  3. self.public_content.save()
  4. self.assertEqual(self.public_content.dict_for_view(self.user), {
  5. "author": self.public_content.author_id,
  6. "author_guid": self.public_content.author.guid,
  7. "author_handle": self.public_content.author.handle,
  8. "author_home_url": self.public_content.author.home_url,
  9. "author_image": self.public_content.author.safer_image_url_small,
  10. "author_is_local": bool(self.public_content.author.user),
  11. "author_name": self.public_content.author.handle,
  12. "author_profile_url": self.public_content.author.get_absolute_url(),
  13. "content_type": self.public_content.content_type.string_value,
  14. "delete_url": reverse("content:delete", kwargs={"pk": self.public_content.id}),
  15. "detail_url": self.public_content.get_absolute_url(),
  16. "formatted_timestamp": self.public_content.timestamp,
  17. "guid": self.public_content.guid,
  18. "has_shared": False,
  19. "humanized_timestamp": "%s (edited)" % self.public_content.humanized_timestamp,
  20. "id": self.public_content.id,
  21. "is_authenticated": True,
  22. "is_author": True,
  23. "is_following_author": False,
  24. "parent": "",
  25. "profile_id": self.public_content.author.id,
  26. "rendered": self.public_content.rendered,
  27. "reply_count": 0,
  28. "reply_url": reverse("content:reply",
  29. "shares_count": 0,
  30. "slug": self.public_content.slug,
  31. "through": self.public_content.id,
  32. "update_url": reverse("content:update",
  33. })
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_is_time_to_run_before_late_metric_slack_time(self):
  2. check_time = datetime.datetime(
  3. year=2016, hour=11,
  4. minute=9, second=59, microsecond=0)
  5. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  6. date_time=(check_time + datetime.timedelta(hours=-1)))
  7. self.assertFalse(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_is_time_to_run_after_late_metric_slack_time(self):
  2. check_time = datetime.datetime(
  3. year=2016, microsecond=1)
  4. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  5. date_time=(check_time + datetime.timedelta(hours=-1)))
  6. self.assertTrue(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_is_time_to_run_with_already_done_this_hour(self):
  2. check_time = datetime.datetime(
  3. year=2016,
  4. minute=30, microsecond=0)
  5. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  6. date_time=check_time)
  7. self.assertFalse(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_is_time_to_run_after_midnight_but_before_late_metric_slack_time(
  2. self):
  3. check_time = datetime.datetime(
  4. year=2016, hour=0,
  5. minute=5, microsecond=0)
  6. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  7. date_time=(check_time + datetime.timedelta(hours=-1)))
  8. self.assertFalse(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_is_time_to_run_after_midnight_and_after_late_metric_slack_time(
  2. self):
  3. check_time = datetime.datetime(
  4. year=2016, microsecond=1)
  5. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  6. date_time=(check_time + datetime.timedelta(hours=-1)))
  7. self.assertTrue(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:monasca-transform    作者:openstack    | 项目源码 | 文件源码
  1. def test_same_time_different_day_behavIoUr(self):
  2. check_time = datetime.datetime(
  3. year=2016, microsecond=1)
  4. PreHourlyProcessorUtil.get_data_provider().set_last_processed(
  5. date_time=(check_time + datetime.timedelta(days=-1)))
  6. self.assertTrue(PreHourlyProcessorUtil.is_time_to_run(check_time))
项目:dsq    作者:baverman    | 项目源码 | 文件源码
  1. def test_crontab():
  2. c = Crontab()
  3. c.add(''boo'')
  4. c.add(''foo'', 0)
  5. c.add(''bar'', [1, 3], -5, -1, 0)
  6.  
  7. assert c.actions(0, 1) == {''boo'', ''foo''}
  8. assert c.actions(1, 1) == {''boo''}
  9. assert c.actions(1, 7) == {''boo'', ''bar''}
  10. assert c.actions(3, ''bar''}
  11.  
  12. ts = mktime(datetime(2016, 17, 1).timetuple())
  13. assert c.actions_ts(ts) == {''boo'', ''bar''}
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
  1. def _get_extensions(self):
  2. pathname = os.path.join(self.dirname, self.filename)
  3. name_ver = ''%s-%s'' % (self.name, self.version)
  4. info_dir = ''%s.dist-info'' % name_ver
  5. arcname = posixpath.join(info_dir, ''EXTENSIONS'')
  6. wrapper = codecs.getreader(''utf-8'')
  7. result = []
  8. with ZipFile(pathname, ''r'') as zf:
  9. try:
  10. with zf.open(arcname) as bf:
  11. wf = wrapper(bf)
  12. extensions = json.load(wf)
  13. cache = self._get_dylib_cache()
  14. prefix = cache.prefix_to_dir(pathname)
  15. cache_base = os.path.join(cache.base, prefix)
  16. if not os.path.isdir(cache_base):
  17. os.makedirs(cache_base)
  18. for name, relpath in extensions.items():
  19. dest = os.path.join(cache_base, convert_path(relpath))
  20. if not os.path.exists(dest):
  21. extract = True
  22. else:
  23. file_time = os.stat(dest).st_mtime
  24. file_time = datetime.datetime.fromtimestamp(file_time)
  25. info = zf.getinfo(relpath)
  26. wheel_time = datetime.datetime(*info.date_time)
  27. extract = wheel_time > file_time
  28. if extract:
  29. zf.extract(relpath, cache_base)
  30. result.append((name, dest))
  31. except KeyError:
  32. pass
  33. return result
项目:nova    作者:hubblestack    | 项目源码 | 文件源码
  1. def _get_x509_days_left(x509):
  2. date_fmt = ''%Y%m%d%H%M%sZ''
  3. current_datetime = datetime.datetime.utcNow()
  4. not_after = time.strptime(x509.get_notAfter(), date_fmt)
  5. not_before = time.strptime(x509.get_notBefore(), date_fmt)
  6.  
  7. ret = {''not_after'': (datetime.datetime(*not_after[:6]) - current_datetime).days,
  8. ''not_before'': (datetime.datetime(*not_before[:6]) - current_datetime).days}
  9.  
  10. return ret
项目:NearBeach    作者:robotichead    | 项目源码 | 文件源码
  1. def time_combined(year,month,day,hour,minute,meridiem):
  2. """
  3. Time is tricky. So I am following the simple rules;
  4. 12:** AM will have the hour changed to 0
  5. 1:** AM will not have the hour changed
  6. 12:** PM will not have the hour changed
  7. 1:** PM will have the hour changed by adding 12
  8.  
  9. From these simple points,I have constructed the following
  10. if statements to take control of the correct hour.
  11. """
  12. if meridiem == "AM":
  13. if hour == 12:
  14. hour = 0
  15. else:
  16. if hour < 12:
  17. hour = hour + 12
  18.  
  19.  
  20.  
  21. # Create the final start/end date fields
  22. return datetime.datetime(
  23. year,
  24. month,
  25. day,
  26. hour,
  27. minute
  28. )
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
  1. def parse_neuralynx_time_string(self, time_string):
  2. # Parse a datetime object from the idiosyncratic time string in Neuralynx file headers
  3. try:
  4. tmp_date = [int(x) for x in time_string.split()[4].split(''/'')]
  5. tmp_time = [int(x) for x in time_string.split()[-1].replace(''.'', '':'').split('':'')]
  6. tmp_microsecond = tmp_time[3] * 1000
  7. except:
  8. warnings.warn(''Unable to parse time string from Neuralynx header: '' + time_string)
  9. return None
  10. else:
  11. return datetime.datetime(tmp_date[2], tmp_date[0], tmp_date[1], # Year,month,day
  12. tmp_time[0], tmp_time[1], tmp_time[2], # Hour,minute,second
  13. tmp_microsecond)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_get_vacations_view_is_working_properly(self):
  2. """testing if GET: /api/users/{id}/vacations view is working properly
  3. """
  4. from stalker import db, Vacation
  5. import datetime
  6. vac1 = Vacation(
  7. user=self.test_user1,
  8. start=datetime.datetime(2016, 24, 0),
  9. end=datetime.datetime(2016, 28, 0)
  10. )
  11.  
  12. vac2 = Vacation(
  13. user=self.test_user1, 0)
  14. )
  15. db.DBSession.add_all([vac1, vac2])
  16.  
  17. db.DBSession.flush()
  18. import transaction
  19. transaction.commit()
  20.  
  21. from stalker import User
  22. user1 = User.query.filter(User.login == self.test_user1.login).first()
  23. response = self.test_app.get(
  24. ''/api/users/%s/vacations'' % self.test_user1.id
  25. )
  26.  
  27. self.assertEqual(
  28. sorted(response.json_body),
  29. sorted([
  30. {
  31. ''id'': v.id,
  32. ''$ref'': ''/api/vacations/%s'' % v.id,
  33. ''name'': v.name,
  34. ''entity_type'': v.entity_type
  35. } for v in [user1.vacations[0], user1.vacations[1]]
  36. ])
  37. )
  38.  
  39. # TASKS
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_update_entity_is_working_properly(self):
  2. """testing if update_entity() method is working properly
  3. """
  4. # create a time log
  5. import datetime
  6. start = datetime.datetime(2016, 26, 16)
  7. end = datetime.datetime(2016, 17)
  8. new_end = datetime.datetime(2016, 18)
  9.  
  10. from stalker import db, TimeLog
  11.  
  12. db.DBSession.flush()
  13. db.DBSession.commit()
  14.  
  15. t1 = TimeLog(
  16. task=self.test_task1,
  17. resource=self.test_user1,
  18. start=start,
  19. end=end,
  20. created_by=self.test_user2
  21. )
  22. db.DBSession.add(t1)
  23. db.DBSession.commit()
  24.  
  25. from stalker_pyramid.testing import DummyRequest, DummyMultiDict
  26. request = DummyRequest()
  27. request.matchdict[''id''] = t1.id
  28. request.params = DummyMultiDict()
  29.  
  30. from stalker_pyramid.views import EntityViewBase
  31. request.params[''end''] = \\
  32. EntityViewBase.milliseconds_since_epoch(new_end)
  33.  
  34. self.patch_logged_in_user(request)
  35. time_log_view = time_log.TimeLogViews(request)
  36.  
  37. response = time_log_view.update_entity()
  38.  
  39. t1_db = TimeLog.query.filter(TimeLog.name == t1.name).first()
  40. self.assertEqual(t1_db.end, new_end)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_delete_entity_is_working_properly(self):
  2. """testing if delete_entity() method is working properly
  3. """
  4. # create a time log
  5. import datetime
  6. start = datetime.datetime(2016, 17)
  7.  
  8. from stalker import db,
  9. created_by=self.test_user2
  10. )
  11. db.DBSession.add(t1)
  12. db.DBSession.commit()
  13.  
  14. from stalker_pyramid.testing import DummyRequest
  15. request = DummyRequest()
  16. request.matchdict[''id''] = t1.id
  17. time_log_view = time_log.TimeLogViews(request)
  18.  
  19. response = time_log_view.delete_entity()
  20.  
  21. self.assertIsNone(
  22. TimeLog.query
  23. .filter(TimeLog.task == self.test_task1)
  24. .filter(TimeLog.resource == self.test_user1)
  25. .first()
  26. )
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_update_entity_is_working_properly_with_post(self):
  2. """testing if POST: /api/time_logs/{id} view is working properly
  3. """
  4. # create a time log
  5. import datetime
  6. start = datetime.datetime(2016,
  7. created_by=self.test_user2
  8. )
  9. db.DBSession.add(t1)
  10. db.DBSession.commit()
  11.  
  12. from stalker_pyramid.views import EntityViewBase
  13.  
  14. self.admin_login()
  15. response = self.test_app.post(
  16. ''/api/time_logs/%s'' % t1.id,
  17. params={
  18. ''end'': EntityViewBase.milliseconds_since_epoch(new_end)
  19. },
  20. status=200
  21. )
  22.  
  23. t1_db = TimeLog.query.filter(TimeLog.name == t1.name).first()
  24. self.assertEqual(t1_db.end, new_end)
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_delete_entity_is_working_properly(self):
  2. """testing if DELETE: /api/time_logs/{id} view is working properly
  3. """
  4. # create a time log
  5. import datetime
  6. start = datetime.datetime(2016,
  7. created_by=self.test_user2
  8. )
  9. db.DBSession.add(t1)
  10. db.DBSession.commit()
  11.  
  12. response = self.test_app.delete(
  13. ''/api/time_logs/%s'' % t1.id,
  14. status=200
  15. )
  16.  
  17. self.assertIsNone(
  18. TimeLog.query
  19. .filter(TimeLog.task == self.test_task1)
  20. .filter(TimeLog.resource == self.test_user1)
  21. .first()
  22. )
项目:stalker_pyramid    作者:eoyilmaz    | 项目源码 | 文件源码
  1. def test_create_entity_with_invalid_user_id(self):
  2. """testing if create_entity() method is working properly with invalid
  3. user_id parameter
  4. """
  5. import datetime
  6. start = datetime.datetime(2016, 22, 10)
  7. end = datetime.datetime(2016, 16)
  8.  
  9. from stalker_pyramid.testing import DummyRequest, DummyMultiDict
  10. from stalker_pyramid.views import EntityViewBase
  11. request = DummyRequest()
  12. request.params = DummyMultiDict()
  13. request.params[''user_id''] = -1
  14. request.params[''start''] = \\
  15. EntityViewBase.milliseconds_since_epoch(start)
  16. request.params[''end''] = EntityViewBase.milliseconds_since_epoch(end)
  17.  
  18. vacation_views = vacation.VacationViews(request)
  19. from pyramid.httpexceptions import HTTPServerError
  20. with self.assertRaises(HTTPServerError) as cm:
  21. vacation_views.create_entity()
  22.  
  23. self.assertEqual(
  24. str(cm.exception),
  25. ''Missing "user_id" parameter''
  26. )

python datetime.datetime

python datetime.datetime

1.datetime.datetime

datetime.datetime类也可以作为方法使用,它的参数有

			year, month=None, day=None, hour=0, minute=0, second=0,
            microsecond=0, tzinfo=None, *, fold=0

通常我们用前六个,也就是年月日,时分秒,其中年月日是必选参数,不选会报错

TypeError: required argument 'day' (pos 3) not found

选了三个参数的话会返回一个格式化时间字符串,

print(datetime.datetime(2021,4,27))
# 输出结果
2021-04-27 00:00:00
它的类型为
<class 'datetime.datetime'>

2.datetime.datetime的方法

datetime.today() 返回本地的时间

print(datetime.datetime.today())

print(type(datetime.datetime.today()))

# 输出结果
2021-04-27 22:01:08.852135

<class ‘datetime.datetime’>

datetime.Now([tz]) 返回本地的时间,不过可以加参数,tz获取当前时区的时间 tz的类型为tzinfo subclass

datetime.datetime.utcNow() 返回utc时区的时间

**datetime.fromtimestamp(timestamp[, tz]):**根据时间戮创建一个datetime对象,参数tz指定时区信息;

a = time.time()

b= datetime.datetime.fromtimestamp(a)

print(b)

print(type(b))

# 输出结果	
2021-04-27 22:12:25.053921
<class 'datetime.datetime'>

datetime.utcfromtimestamp(timestamp):根据时间戮创建一个datetime对象;

datetime.strptime(date_string, format): 将格式化的时间字符串转换为datetime对象

a = '2021-04-27 22:12:25'

b = datetime.datetime.strptime(a,'%Y-%m-%d %H:%M:%s')

print(type(b))

# 输出结果
<class 'datetime.datetime'>

Python datetime.datetime 模块-astimezone() 实例源码

Python datetime.datetime 模块-astimezone() 实例源码

Python datetime.datetime 模块,astimezone() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用datetime.datetime.astimezone()

项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def parse(cls, report, objects, data, localcontext):
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = datetime.Now()
  12. localcontext[''print_date''] = datetime.astimezone(dt.replace(
  13. tzinfo=pytz.utc), timezone)
  14. localcontext[''print_time''] = localcontext[''print_date''].time()
  15.  
  16. return super(PatientEvaluationReport, cls).parse(report,
  17. localcontext)
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def parse(cls,
  2. localcontext)
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
  1. def normalize(self, dt, is_dst=False):
  2. ''''''Correct the timezone information on the given datetime.
  3.  
  4. This is normally a no-op,as StaticTzInfo timezones never have
  5. ambiguous cases to correct:
  6.  
  7. >>> from pytz import timezone
  8. >>> gmt = timezone(''GMT'')
  9. >>> isinstance(gmt,StaticTzInfo)
  10. True
  11. >>> dt = datetime(2011,5,8,1,2,3,tzinfo=gmt)
  12. >>> gmt.normalize(dt) is dt
  13. True
  14.  
  15. The supported method of converting between timezones is to use
  16. datetime.astimezone(). Currently normalize() also works:
  17.  
  18. >>> la = timezone(''America/Los_Angeles'')
  19. >>> dt = la.localize(datetime(2011,7,3))
  20. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  21. >>> gmt.normalize(dt).strftime(fmt)
  22. ''2011-05-07 08:02:03 GMT (+0000)''
  23. ''''''
  24. if dt.tzinfo is self:
  25. return dt
  26. if dt.tzinfo is None:
  27. raise ValueError(''Naive time - no tzinfo set'')
  28. return dt.astimezone(self)
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_start_date(self, name):
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = self.evaluation_start
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone).date()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_start_time(self, timezone).time()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_end_date(self, name):
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = self.evaluation_end
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone).date()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_end_time(self, timezone).time()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_prescription_date(self, name):
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = self.prescription_date
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone).date()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_prescription_time(self, timezone).time()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_evaluation_date(self, timezone).date()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_evaluation_time(self, timezone).time()
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_print_date():
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = datetime.Now()
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone)
项目:health-mosconi    作者:GNUHealth-Mosconi    | 项目源码 | 文件源码
  1. def get_report_surgery_time(self, name):
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = self.surgery_date
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone).time()
项目:Texty    作者:sarthfrey    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:aws-ops-automator    作者:awslabs    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:epg-dk.bundle    作者:ukdtom    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:userbase-sns-lambda    作者:fartashh    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:Callandtext    作者:iaora    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:start    作者:argeweb    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:alexa-apple-calendar    作者:zanderxyz    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:amazon-alexa-twilio-customer-service    作者:ameerbadri    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_start_date(self, timezone).date()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_start_time(self, timezone).time()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_end_date(self, timezone).date()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_end_time(self, timezone).time()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_prescription_time(self, timezone).time()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_evaluation_date(self, timezone).date()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_evaluation_time(self, timezone).time()
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_print_date():
  2. Company = Pool().get(''company.company'')
  3.  
  4. timezone = None
  5. company_id = Transaction().context.get(''company'')
  6. if company_id:
  7. company = Company(company_id)
  8. if company.timezone:
  9. timezone = pytz.timezone(company.timezone)
  10.  
  11. dt = datetime.Now()
  12. return datetime.astimezone(dt.replace(tzinfo=pytz.utc), timezone)
项目:gnuhealth-live    作者:kret0s    | 项目源码 | 文件源码
  1. def get_report_surgery_date(self, timezone).date()
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:Alexa-Chatter    作者:ekt1701    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:alfredToday    作者:jeeftor    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:alexa-ive-fallen-and-cant-get-up    作者:heatherbooker    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:SenateCaller    作者:tcash21    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:cloud-memory    作者:onejgordon    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:pmatic    作者:larsMichelsen    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:FMoviesPlus.bundle    作者:coder-alpha    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:ebs-snapshot-scheduler    作者:awslabs    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:pyfiddleio    作者:priyankcommits    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:noobotkit    作者:nazroll    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:LSTM-GA-StockTrader    作者:MartinLidy    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:alexa-spark    作者:ismailakkila    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:hackathon    作者:vertica    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)
项目:Chorus    作者:DonaldBough    | 项目源码 | 文件源码
  1. def normalize(self,3))
  2. >>> fmt = ''%Y-%m-%d %H:%M:%s %Z (%z)''
  3. >>> gmt.normalize(dt).strftime(fmt)
  4. ''2011-05-07 08:02:03 GMT (+0000)''
  5. ''''''
  6. if dt.tzinfo is self:
  7. return dt
  8. if dt.tzinfo is None:
  9. raise ValueError(''Naive time - no tzinfo set'')
  10. return dt.astimezone(self)

今天关于如何在 Python 中使用 DateTimepython datetime怎么用的介绍到此结束,谢谢您的阅读,有关python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)、Python datetime 模块-datetime() 实例源码、python datetime.datetime、Python datetime.datetime 模块-astimezone() 实例源码等更多相关知识的信息可以在本站进行查询。

本文标签: